[英]SQL query - Limit results if no match
Background: 背景:
This is a query for searching a db full of products and the SQL is built on the fly depending on what the user has searched. 这是一个用于搜索数据库的产品的查询,SQL是根据用户搜索的内容动态构建的。
SELECT *
FROM gifts
LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id
LEFT JOIN tags ON tags.id = tags_gifts.tag_id
WHERE published = '1'
AND ( (tags_gifts.tag_id = '887') )
GROUP BY gifts.gift_id
ORDER BY COUNT(*) DESC , gift_popularity DESC
This is working as planned however the next part I am trying to do I am struggling with. 这正在按计划进行,但是我正在努力的下一部分正在苦苦挣扎。
I have another table ' tags_gifts_occasion_specific ' which has columns of ' gift_id ' and ' tag_id ' 我有另一个表' tags_gifts_occasion_specific ',其中有' gift_id '和' tag_id '列
Basically if a user searches like the above but there is no tag_id to search for or the tag_id they have searched for does not match the one in tags_gifts_occasion_specific.tag_id then I want to exclude those results. 基本上,如果用户进行上述搜索,但没有要搜索的tag_id或他们搜索的tag_id与tag_gifts_occasion_specific.tag_id中的tag_id不匹配,那么我想排除这些结果。
Do I need to do another select statement inside this one to achieve this? 我是否需要在此语句内执行另一条select语句以实现这一目标? Hope this makes sense 希望这有意义
Try this : 尝试这个 :
SELECT *
FROM gifts AS g
LEFT JOIN tags_gifts_occasion_specific AS os ON g.gift_id = os.gift_id
LEFT JOIN tags_gifts ON tags_gifts.gift_id = gifts.gift_id
LEFT JOIN tags ON tags.id = tags_gifts.tag_id
WHERE published = '1'
AND (os.tag_id IS NULL OR os.tag_id = '887')
AND tags_gifts.tag_id = '887'
GROUP BY gifts.gift_id
ORDER BY COUNT(*) DESC , gift_popularity DESC
This was solved in the end by doing the following: 最终通过执行以下操作解决了此问题:
AND NOT EXISTS ( SELECT * FROM tags_gifts_occasion_specific WHERE tags_gifts_occasion_specific.gift_id = gifts.gift_id)
Then for searches where tags have been included: 然后进行搜索,其中已包含标签:
AND NOT EXISTS ( SELECT * FROM tags_gifts_occasion_specific WHERE tags_gifts_occasion_specific.gift_id = gifts.gift_id AND tags_gifts_occasion_specific.tag_id != '971' )
Thanks okio for your help - it was your answer which led me in the right direction :-) 感谢okio的帮助-正是您的回答使我朝着正确的方向发展:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.