Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on (b.TagId = c.TagId)
where c.TagName = 'FISH'
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on ( b.TagId = c.TagId)
where c.TagName = 'STEAK'
我知道可能有一个相当简单的解决方案,但我无法弄明白
我想获得所有在“标签”的ProductTags表中都有条目的产品。
新查询
原件:
SELECT *
FROM ProductTags as a
JOIN Tags as b on (a.TagId = b.TagId)
WHERE b.TagName = 'FISH'
SELECT *
FROM ProductTags as a
JOIN Tags as b on (a.TagId = b.TagId)
WHERE b.TagName = 'STEAK'
解 选择a.ProductId 从ProductTags作为 将标签加入为b(a.TagId = b.TagId) 在哪里b.TagName('FISH','STEAK')
我想我需要一个HAVING条款? IDK
答案 0 :(得分:3)
您只需要一个IN
条件:
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on (b.TagId = c.TagId)
where c.TagName IN ('FISH', 'STEAK')
您可以在IN
子句中添加任意数量的文字,只要它们以逗号分隔即可。
根据更新的问题进行修改:
如果您想获得多个类别匹配的所有ProductId
,您可以这样做:
SELECT ProductTags.ProductId
FROM ProductTags
WHERE
-- Pull all matches of FISH
ProjectTags.TagId IN (SELECT TagId
FROM Tags
WHERE TagName = 'FISH')
AND
-- Pull all matches of STEAK
ProjectTags.TagId IN (SELECT TagId
FROM Tags
WHERE TagName = 'STEAK')
答案 1 :(得分:1)
如果您想要返回所有STEAK和FISH,您可以使用简单的OR条件:
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on ( b.TagId = c.TagId)
where c.TagName = 'STEAK' OR c.TagName = 'FISH'
答案 2 :(得分:1)
这就是关系分工,我今天早些时候在Meta提出了这个问题。您可以使用子查询。外部查询将拉出与“Fish”匹配的所有行,内部查询将仅选择与“Steak”匹配的行。试试这个:
SELECT a.product_id
FROM producttags a
JOIN tags b ON b.tagid = a.tagid
WHERE b.tagname = 'Fish' AND a.product_id IN(
SELECT a.product_id
FROM producttags a
JOIN tags b ON b.tagid = a.tagid
WHERE b.tagname = 'Steak'
修改强>
如果需要添加其他代码,您可以在IN
子句中添加更多WHERE
个运算符:
SELECT a.product_id
FROM producttags a
JOIN tags b ON b.tagid = a.tagid
WHERE b.tagname = 'Fish'
AND a.product_id IN(
SELECT a.product_id
FROM producttags a
JOIN tags b ON b.tagid = a.tagid
WHERE b.tagname = 'Steak')
AND a.product_id IN(
SELECT a.product_id
FROM producttags a
JOIN tags b ON b.tagid = a.tagid
WHERE b.tagname = 'Chicken')