修复hackish SQL where子句

时间:2012-07-04 14:48:52

标签: php mysql where-clause where

我有两个表,activitiesactivity_toursactivities有许多activity_tours,并且与activities.id>相关联activity_tours.activity_id。我编写了以下SQL来选择具有两个条件的表中的行。

  1. 如果它有某个activity_tours.tour_type OR
  2. 活动有多个游览
  3. 查询看起来有点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)
        )
    

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