mysql - 如何组合两个不同的 mysql where 子句,每个子句产生 5 行

标签 mysql select left-join union where-clause

我使用以下两个查询从每个查询中获取 5 行并显示在一个列表中。有没有可能组合两个查询的方法,这样我就不必单独运行它们。但仍然得到相同的结果,首先是第一个 where 子句的结果,然后是第二个 where 子句的结果。

    SELECT *
    FROM
    institutes
    LEFT JOIN city ON institutes.city_id = city.city_id 
    LEFT JOIN district ON city.district_id = district.district_id 
    WHERE
    city.city_id = $current_city_id ORDER BY RAND() DESC LIMIT 5


    SELECT *
    FROM
    institutes
    LEFT JOIN city ON institutes.city_id = city.city_id 
    LEFT JOIN district ON city.district_id = district.district_id 
    WHERE
    district.district_id = $current_district_id ORDER BY RAND() DESC LIMIT 5 

最佳答案

UNION ALL 与包装器 SELECT 一起使用:

SELECT * FROM (
    SELECT *
    FROM institutes
    LEFT JOIN city ON institutes.city_id = city.city_id 
    LEFT JOIN district ON city.district_id = district.district_id 
    WHERE city.city_id = $current_city_id
    ORDER BY RAND() DESC LIMIT 5
) x1
UNION ALL
SELECT * FROM (
    SELECT *
    FROM institutes
    LEFT JOIN city ON institutes.city_id = city.city_id 
    LEFT JOIN district ON city.district_id = district.district_id 
    WHERE district.district_id = $current_district_id
    ORDER BY RAND() DESC LIMIT 5 
) x2

需要包装器SELECT,因为您无法在同一级别组合ORDER BY ... LIMITUNION,但是您可以ORDER BY ... LIMIT放入子查询中。

UNION ALL 是必需的,而不仅仅是 UNION,因为 UNION 会删除重复项,而您的问题需要保留重复项。

UNION ALL 也比 UNION 更快(因为它不需要去重,这通常需要排序),但在这种情况下,行数太少了性能上的差异不会被注意到,但在未来的应用程序中最好记住这一点。

关于mysql - 如何组合两个不同的 mysql where 子句,每个子句产生 5 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690714/

相关文章:

php - 使用 session 数据将帖子链接到用户 ID

mysql - 回历日期格式到 mysql(无效范围)

php - 通过 AJAX 请求从 MySQL 数据库获取大数据

php - Mysql,选择按不同列分组的 id(为每个唯一域选择所有 id)

mysql - 多重连接过滤

java - 如何计算java中两个日期之间的准确月份差异

mysql - SQL : Select the max of two occurrences

sql - 当我添加一个 LEFT OUTER JOIN 时,查询只返回几行

sql - 左加入 Group By

sql - 如何将 2 个 select 语句合并为一个?