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

时间:2018-08-05 01:15:46

标签: 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 

2 个答案:

答案 0 :(得分:2)

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合并在同一级别,但是您可以放置{{1} }在子查询中。

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

UNION也比UNION ALL快(因为它不必进行重复数据删除,这通常需要排序),但是在这种情况下,行数很少,因此性能差异不会请注意,但是在以后的应用中记住这一点是很好的。

答案 1 :(得分:0)

我尝试了@Bohemian的答案,但是它对我没有用。多亏了他的简单解释,并遵循了link,我才能够提出以下对我有用的代码。但是我不知道是否有一种方法可以摆脱与代码中的左联接相关的冗余

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