gpt4 book ai didi

php - 修复骇人听闻的 SQL where 子句

转载 作者:行者123 更新时间:2023-11-30 23:29:47 25 4
gpt4 key购买 nike

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

  1. 如果它具有特定的activity_tours.tour_type
  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)
)

最佳答案

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

关于php - 修复骇人听闻的 SQL where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11331346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com