我有两个表,activities
和activity_tours
。 activities
有许多activity_tours
,并且与activities.id
>相关联activity_tours.activity_id
。我编写了以下SQL来选择具有两个条件的表中的行。
activity_tours.tour_type
OR 查询看起来有点hackish。有人可以帮助我提高查询效率。
SELECT SQL_CALC_FOUND_ROWS
activities.activity_name,
activities.image_path,
activity_tours.tour_type
FROM
activities
LEFT JOIN activity_tours ON activities.id = activity_tours.activity_id
WHERE
(
activity_tours.tour_type != 17 OR (
(SELECT count(*) FROM activity_tours WHERE activity_id = activities.id) > 1)
)
答案 0 :(得分:0)
SELECT a.activity_name,
a.image_path,
at.tour_type,
MAX(at.tour_type != 17) AS tour_not_17,
COUNT(*) AS tour_count
FROM activities a
INNER JOIN activity_tours at ON a.id = at.activity_id
GROUP BY a.activity_name, a.image_path
HAVING tour_not_17 OR tour_count > 1
不知道如何处理tour_type
列;应该使用聚合,但我无法弄清楚哪一个。也许你可以做GROUP_CONCAT()
?