有没有办法做一个单一的选择从汽车桌上获得10辆最新的汽车,其中5辆是红色的,5辆是蓝色的?
我能想到的最好的是两个选择和一个程序化合并:
red = query("select * from cars where color = 'red' order by when desc limit 5")
blue = query("select * from cars where color = 'blue' order by when desc limit 5")
all = merge(red, blue)
答案 0 :(得分:2)
对于MySQL,请尝试:
select * from cars where color = 'blue' order by releasedate desc limit 5
Union
select * from cars where color = 'red' order by releasedate desc limit 5
答案 1 :(得分:0)
因为,mysql不像任何其他RDBMS一样支持CTE
和Window Function
,所以可以在此使用相关子查询,
SELECT a.*
FROM Cars a
WHERE a.Color IN ('Red', 'Blue') AND
(
SELECT COUNT(*)
FROM Cars b
WHERE b.Color IN ('Red', 'Blue') AND
a.Color = b.Color AND
a.time >= b.time
) <= 5
<强> POSTGRESQL 强>
WITH carList
AS
(
SELECT Col1, Col2, Col3, Color,
ROW_NUMBER() OVER (PARTITION BY Color ORDER BY time DESC) rn
FROM tableName
)
SELECT Col1, Col2, Col3, Color
FROM carList
WHERE Color IN ('Red', 'Blue') AND
RN <= 5