+-
PHP MySQL查询搜索与外键
我的数据库中有2个表,例如tb_device和tb_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_label的ID.我要搜索带有三星,苹果,戴尔等标签名称的标签,而不是数字.我的搜索代码:

$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

说明:dell的ID号为3,结果显示tb_device的ID号为3.有什么解决方案可以显示正确的结果?

对不起英语不好

最佳答案
您在查询中错过了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
        ";
点击查看更多相关文章

转载注明原文:PHP MySQL查询搜索与外键 - 乐贴网