我有这张表:
产品 - > hasMany - >类
表:产品
+----+--------+
| id | title |
+----+--------+
| 1 | Prod 1 |
| 2 | Prod 2 |
| 3 | Prod 3 |
+----+--------+
表:类别
+----+-------+------------+
| id | title | product_id |
+----+-------+------------+
| 1 | Cat 1 | 1 |
| 2 | Cat 2 | 1 |
| 3 | Cat 3 | 2 |
| 4 | Cat 1 | 1 |
+----+-------+------------+
我如何在我的例子中查询属于“Cat 1”和“Cat 2”两类的产品我只想找到“Prod 1”
答案 0 :(得分:1)
我的直觉是你应该改变数据库,所以你要有一个habtm关系。
所以你的表应该是这样的:
Products (id, title)
ProductCategories (product_id, category_id)
Categories (id, title)
因此该产品可以属于多个类别。
然后,您可以通过以下查询在表格中查找属于ID = 1的类别和ID = 3的类别的产品:
MySQL查询
SELECT Products.id, Products.title
FROM Products
WHERE
Products.id IN
(
SELECT c1.product_id
FROM ProductCategories AS c1
INNER JOIN ProductCategories AS c2
ON c1.product_id = c2.product_id
WHERE c1.category_id = 1 AND c2.category_id = 3
);