表格结构
类别表
id name
23 Rifle
24 Bow
26 Black Powder
Outfitters表
id name
1 jignesh
2 Ram
3 Ravi
outfitters类别表
id outfitters_id categories_id
1 1 23
2 1 24
3 1 26
4 2 23
5 2 26
6 3 26
现在我的问题是什么时候选择(步枪和黑粉)手段(23,26) 结果应该是
1 jignesh
2 Ram
当前查询
SELECT distinct outfitters.id,
outfitters.name,
FROM outfitters
LEFT JOIN categories as c1 ON (c1.categories_id='23')
LEFT JOIN categories as c2 ON (c2.categories_id='26')
WHERE outfitters.id=c1.outffiters_id
OR
outfitters.id=c2.outffiters_id
AND outfitters.of_active=1
答案 0 :(得分:0)
试试这个
SELECT distinct outfitters.id,
outfitters.name,
FROM outfitters
LEFT JOIN categories as c1 ON (c1.categories_id='23')
LEFT JOIN categories as c2 ON (c2.categories_id='26')
WHERE (outfitters.id=c1.outffiters_id
OR
outfitters.id=c2.outffiters_id)
AND outfitters.of_active=1
GROUP BY outfitters.name
好的,你可以用这样的子查询来做到这一点
SELECT name, id FROM(
SELECT outfitters.name, outfitters.id, GROUP_CONCAT(outfitters_categories.categories_id) as gc
FROM outfitters
JOIN outfitters_categories ON (outfitters.id = outfitters_categories.outfitters_id)
WHERE outfitters_categories.categories_id IN (23,26)
GROUP BY outfitters.id )
tmp WHERE gc = "23,26"
然后你可以简单地用用户选择的任何内容替换23,26
答案 1 :(得分:0)
如果您需要必须属于您的2个类别的户外用品商品,您可以通过获取每个必须>>的服装商的明确计数来实现此目的。或= 2以及您的where过滤器,根据提供的样本数据集
查看小提琴示例SELECT
o.*
FROM
Outfitters o
JOIN outfitters_categories oc
ON (o.id = oc.outfitters_id)
WHERE oc.categories_id IN (23, 26)
GROUP BY o.id
HAVING COUNT(DISTINCT oc.categories_id) >= 2