我的数据库中有 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
。我想搜索标签名称为 samsung
、apple
、dell
的标签,而不是数字。我的搜索代码:
$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
,结果显示id
号3
来自 tb_device
。有什么解决方案可以显示正确的结果吗?
抱歉英语不好
最佳答案
您在查询中遗漏了 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 查询搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51490480/