我有3张桌子。
巡视可以有多个标签和多个主题。所以我要写什么和sql语句来查找指定的游览。例如,查找标签id = 10和15以及主题id = 36和45的旅行。
SELECT DISTINCT (t1.id) FROM optional AS t1
LEFT JOIN optional_theme_rel as t3 ON t3.tour_id = t1.id AND (t3.theme_id =36 OR t3.theme_id =45)
LEFT JOIN optional_tag_rel as t2 ON t2.tour_id = t1.id AND (t2.tag_id = 10 OR t2.tag_id =15)
GROUP BY optional.id
这些语句获取主题id = 36或45的所有记录,但我需要使用AND语句,但是当我使用AND代替OR时,它不显示任何记录。在sql上必须有不同的方法,但我不太了解它。
答案 0 :(得分:0)
IN
语法group by
(你没有聚合功能)AS
的位置略有偏差试试这个:
SELECT DISTINCT t1.id
FROM optional t1
LEFT JOIN optional_theme_rel as t3 ON t3.tour_id = t1.id AND t3.theme_id in (36, 5)
LEFT JOIN optional_tag_rel as t2 ON t2.tour_id = t1.id AND t2.tag_id in (10, 15)
答案 1 :(得分:0)
如果我理解你想要同时具有两个主题(使用theme_id = 36和45)和两个标签(tag_id = 10和15)的游览,那么你既不需要GROUP BY
也不需要{{1 }}
但是,实现此目的的一种方法是将每个辅助表连接两次:
DISTINCT
获得相同结果的另一种方法是:
SELECT op.id
FROM optional AS op
JOIN optional_theme_rel AS theme1
ON theme1.tour_id = op.id
AND theme1.theme_id = 36
JOIN optional_theme_rel AS theme2
ON theme2.tour_id = op.id
AND theme2.theme_id = 45
JOIN optional_tag_rel AS tag1
ON tag1.tour_id = op.id
AND tag1.tag_id = 10
JOIN optional_tag_rel AS tag2
ON tag2.tour_id = op.id
AND tag2.tag_id = 15