2

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

目前我正在使用UNION ALLORDER BY Date DESC

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

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

第一条记录将是从表中添加的最新记录A,然后是从表中添加的最新记录,然后B是. 像这样循环它们?CD

谢谢

4

2 回答 2

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)

于 2012-12-05T20:14:19.680 回答
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
于 2012-12-05T20:32:48.963 回答