CustomerID cat_id ContactName Address City PostalCode Country
1 Alfreds 13 Maria Anders Obere Str Berlin 12209 Germany
4 Around 13,14 Thomas Hardy 120 Hanov London WA1 1DP UK
获取14个数据的查询是什么? 我试过了
SELECT *
FROM `customers`
WHERE cat_id IN (13,14)
但失败了。
答案 0 :(得分:2)
修复您的数据模型!为什么这是错的?
因此,您应该有一个表格,每个customer_id
和cat_id
有一行。这通常被称为"联合表"或"关联表"。
也就是说,有时我们会遇到其他人真正的,非常非常糟糕的设计决策。如果是这样,您可以使用find_in_set()
:
where find_in_set(13, cat_ids) > 0 and -- or is that "or"
find_in_set(14, cat_ids) > 0
答案 1 :(得分:1)
您可以使用FIND_IN_SET
:
SELECT *
FROM `customers`
WHERE FIND_IN_SET(13, `cat_id`) > 0 OR FIND_IN_SET(14, `cat_id`) > 0
注意:您不应该存储这样的值!
您的表格应如下所示,以避免使用FIND_IN_SET
:
表customers
:
CustomerID | ContactName | Address | City | PostalCode | Country
1 | Maria Anders | Obere Str | Berlin | 12209 | Germany
4 | Thomas Hardy | 120 Hanov | London | WA1 1DP | UK
表customers_cats
:
customer_id | cat_id
1 | 13
4 | 13
4 | 14
表cats
:
CatID | Column1
---------------
13 | abc
14 | def
因此查询将如下所示:
SELECT c.*
FROM `customers` c LEFT JOIN `customers_cats` cc ON c.CustomerID = cc.customer_id
WHERE cc.cat_id IN (13, 14)
答案 2 :(得分:0)
这样的事情应该有效:
SELECT * FROM $ tbls WHERE CONCAT(',',cat_id,',')LIKE'%,14,%&#39 ;;
虽然你应该考虑将其正常化。