1

我有两张桌子,activitiesactivity_toursactivitieshasManyactivity_toursactivities.id>相关activity_tours.activity_id。我编写了以下 SQL 来选择两个表中具有两个条件之一的行。

  1. 如果它有一定的activity_tours.tour_typeOR
  2. 该活动有不止一次旅行

该查询似乎有点骇人听闻。有人可以帮我提高这个查询的效率。

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)
    )
4

1 回答 1

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()

于 2012-07-04T14:56:18.257 回答