我做错了什么?如您所见,139在第3行。但它仍然返回false
id | babu | anum
--------------------
1 | 76 | 34,21,421
2 | 76 | 345,948,21,433
3 | 76 | 634,35,11,65,139
4 | 76 | 4366,25,74,9
$a = $db->query("SELECT * FROM umaga WHERE babu = 76")->fetch();
$list_of_ids = explode(',', $a['anum']);
echo in_array(139, $list_of_ids) ? 'ID 139 does exist in a row' : 'There is no row that contains that id';
答案 0 :(得分:3)
我完全同意其他人的观点,即您可以更好地规范化数据。但如果出于某种原因不能选择尝试使用FIND_IN_SET()
SELECT *
FROM umaga
WHERE babu = 76
AND FIND_IN_SET('139', anum) > 0
输出:
| ID | BABU | ANUM | -------------------------------- | 3 | 76 | 634,35,11,65,139 |
这是 SQLFiddle 演示
现在php代码可能看起来像
$sql = "SELECT COUNT(*) FROM umaga WHERE babu = 76 AND FIND_IN_SET('139', anum) > 0";
$result = $db->query($sql)->fetch();
echo $result ? 'ID 139 does exist in a row' : 'There is no row that contains that id';
答案 1 :(得分:0)
就像你现在看到的那样,这只会让你感到头痛。规范化你的表格。然后你可以正常选择。
看起来应该是这样的
id | babu | anum
--------------------
1 | 76 | 34
1 | 76 | 21
1 | 76 | 421
2 | 76 | 345
2 | 76 | 948
2 | 76 | 21
2 | 76 | 433
...
答案 2 :(得分:0)
我相信你必须使用fetch
来循环结果,如
while($a = $db->query("SELECT * FROM umaga WHERE babu = 76")->fetch()){
$list_of_ids = explode(',', $a['anum']);
echo in_array(139, $list_of_ids) ? 'ID 139 does exist in a row' : 'There is no row that contains that id';
}
作为附注,或者应该是主要注释,强烈建议不要存储逗号分隔数据
答案 3 :(得分:0)
除了缺少查询的规范化之外,还从数据库中获取所有行。你必须遍历它们或在where子句中使用ID