-3

有没有什么办法可以从汽车表中获得 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)
4

2 回答 2

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
于 2013-03-31T14:27:13.577 回答
0

由于 mysql 不支持CTE并且Window Function与任何其他 RDBMS 一样,您可以在此使用相关子查询,

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
于 2013-03-31T14:20:27.543 回答