PHP MySQL 使用外键查询搜索

PHP MySQL Query Search with Foreign Key

我的数据库中有 2 个表,tb_devicetb_label 其中包含例如:

tb_device
id (AI)  |   type  |  label  |  etc
-------------------------------------
  1      |   A123  |    1    |  test
  2      |   A561  |    3    |  test2
  3      |   A777  |    2    |  test3
  4      |   A222  |    3    |  test4

tb_label
id (AI)  |  label
-------------------
  1      |  Samsung
  2      |  Apple
  3      |  Dell

而且我已经创建了显示 tb_devices 的 CRUD 表单 (PHP)。这个 CRUD 在每一列上都有一个搜索表单。其他列用于搜索,但标签列不起作用,因为它包含来自 tb_labelid。我想搜索带有 samsungappledell 等标签名称的标签,而不是数字。我的搜索代码:

$sql = "SELECT *
            FROM tb_device a, tb_label b
            WHERE
                type LIKE '%".@$_POST['type']."%' AND
                (a.label=b.id AND b.label LIKE '%".@$_POST['label']."%') AND
                etc LIKE '%".@$_POST['etc']."%'
            ORDER BY type
    ";

我尝试输入dell,但是结果:

      3      |   A777  |    2    |  test3

解释:dellid3,结果显示 tb_deviceid3。是否有任何解决方案可以显示正确的结果?

抱歉英语不好

您在查询中遗漏了 b.label

 $sql = "SELECT a.*, b.label
                FROM tb_device a, tb_label b
                WHERE
                    a.type LIKE '%".@$_POST['type']."%' AND
                    (a.label=b.id AND b.label LIKE '%".@$_POST['label']."%') AND
                    etc LIKE '%".@$_POST['etc']."%'
                ORDER BY a.type
        ";

我相信你应该只有 tb_label.label =(你的用户输入变量:Dell)

的 WHERE

我相信你想做一个

INNER JOIN tb_label
ON tb_device.label = tb_label.id