如何返回与查询结果相关的所有类别 ID?
items_cats: (many to many)
product_id | category_id
====================
1 | 1
1 | 2
1 | 4
1 | 7
2 | 1
2 | 3
2 | 4
2 | 7
3 | 1
3 | 3
3 | 4
3 | 8
在下面的查询中,我得到了所有包含 category_id 3 和 category_id 7 的产品 ID。
但我也想知道哪些 category_id 的(选项)仍然有 producs_id 的选择基础:
例如,我喜欢这个查询返回(基于代码示例):
-product_id = 2
-category_id's: 7, 3, 4, 1
使用此功能时,我可能希望限制每页最大项目数的查询。
到目前为止我得到的代码:
SELECT
DISTINCT t1.product_id, t1.category_id
FROM
items_cats t1
INNER JOIN
items_cats t1b
ON t1.product_id =t1b.product_id
WHERE
t1.category_id=3 AND
t1b.category_id=7
松散查询猫 ID 的问题:
SELECT
e1.category_id
FROM
drinks_ingredients e1
WHERE
e1.category_id=2
当然它会返回 2,但我喜欢它返回 1、2、4、7。
反过来说,如果有很多产品和类别,我该如何提高效率呢?我可以组合这些查询吗?
SELECT DISTINCT
t1.category_id
FROM items_cats t1
WHERE t1.product_id = 2
最佳答案
我敢肯定还有其他方法可以做到这一点,但这里有一个。
首先,我们需要弄清楚我们对哪些 product_id
感兴趣。您可以计算每个 product_id
属于多少个必需类别:
SELECT product_id, count(category_id) as numcats
FROM items_cats
WHERE category_id IN (3,7)
GROUP BY product_id;
+------------+---------+
| product_id | numcats |
+------------+---------+
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
+------------+---------+
由于我们指定了两个 category_id
(3 和 7),我们只对 product_id
感兴趣,其中 count(category_id) = 2
。所以在最后添加一个HAVING numcats=2
:
SELECT product_id, COUNT(category_id) as numcats
FROM items_cats
WHERE category_id IN (3,7)
GROUP BY product_id
HAVING numcats=2;
# (returns all product_id with both category_id=3 and 7.
这里是我们想要 category_id
的所有 product_id
。
然后我们只选择所有category_id
where product_id
is in the previous table:
SELECT DISTINCT category_id
FROM items_cats
WHERE product_id IN
(SELECT product_id
FROM items_cats
WHERE category_id IN (3,7)
GROUP BY product_id
HAVING COUNT(category_id)=2);
+-------------+
| category_id |
+-------------+
| 1 |
| 3 |
| 4 |
| 7 |
+-------------+
关于mysql - 根据结果消除空类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8819038/