Mysql按日期订购,但过滤结果

时间:2012-12-05 19:58:17

标签: mysql

假设我有4个表A,B,C,D,每个表中都有记录和datetime字段。

目前正在使用UNION ALLORDER BY Date DESC

问题是如果表A今天添加了10条记录,而表B昨天添加了10条记录,那么前10条结果全部来自表A

是否可以获取按日期排序的记录,但是在所有4个表之间混合?

第一条记录将是表格A中添加的最新记录,然后是表格B中添加的最新记录,然后是C,然后是D。并像那样循环它们?

感谢

2 个答案:

答案 0 :(得分:1)

我不确定这是你在寻找什么,但我认为你可以使用这样的东西:

SELECT
  A.*,
  datediff((select max(`date`) from A), `date`) as d_diff,
  1 as tab
FROM A
UNION ALL
SELECT
  B.*,
  datediff((select max(`date`) from B), `date`) as d_diff,
  2 as tab
FROM B
ORDER BY d_diff, tab, `date` desc

或者这个:

SELECT * FROM (SELECT  A.* FROM A ORDER BY `date` desc limit 5) a
UNION ALL
SELECT * FROM (SELECT  B.* FROM B ORDER BY `date` desc limit 5) b
ORDER BY `date` DESC

根据您的评论,这应该有效,但也可能很慢:

SELECT
  A.*,
  (select count(*) from A A1 where A1.dat>A.dat) as i,
  1 as tab
FROM A
UNION ALL
SELECT
  B.*,
  (select count(*) from B B1 where B1.dat>B.dat) as i,
  2 as tab
FROM B
order by i, tab

(使用变量可以更快,但我更喜欢普通的SQL)

答案 1 :(得分:1)

不幸的是,MySQL没有排名功能 - 但你可以用变量来模拟它。我建议尝试以下内容:

SELECT * FROM 
(select *, @rownum := @rownum + 1 AS rank, 'A' as tbl 
 from (SELECT * FROM (SELECT  A.* FROM A ORDER BY `date` desc) sa) a, 
      (SELECT @rownum := 0) r
 union all
 select *, @rownum2 := @rownum2 + 1 AS rank, 'B' as tbl 
 from (select * from (SELECT  B.* FROM B ORDER BY `date` desc) sb) b, 
      (SELECT @rownum2 := 0) r2
 union all
 select *, @rownum3 := @rownum3 + 1 AS rank, 'C' as tbl 
 from (select * from (SELECT  C.* FROM C ORDER BY `date` desc) sc) c, 
      (SELECT @rownum3 := 0) r3
 union all
 select *, @rownum4 := @rownum4 + 1 AS rank, 'D' as tbl 
 from (select * from (SELECT  D.* FROM D ORDER BY `date` desc) sd) d, 
      (SELECT @rownum4 := 0) r4
) s
order by rank, tbl

或者,尝试类似:

SELECT * FROM 
(SELECT S.*, 
        @rownum := CASE WHEN @tblvar <> S.tbl THEN 0 ELSE @rownum+1 END AS rank, 
        @tblvar := S.tbl AS tblvar 
 FROM 
 (SELECT * FROM 
  (SELECT  A.*, 'A' as tbl FROM A
   UNION ALL
   SELECT  B.*, 'B' as tbl FROM B
   UNION ALL
   SELECT  C.*, 'C' as tbl FROM C
   UNION ALL
   SELECT  D.*, 'D' as tbl FROM D) U
  ORDER BY tbl, `date` desc) S,
 (SELECT @rownum := 0) R,
 (SELECT @tblvar := '!') T
) Q
order by rank, tbl