按时间顺序从不同的表中获取帖子

时间:2014-08-21 10:18:24

标签: php mysql sql datetime

我有4个mysql表,即post_type1post_type2post_type3post_type4。这4张桌子有不同的号码。列和不同的结构。其中的常用列是'id',它是主键,time(datetime)是写入帖子的时间。 如果我要从表中获取最后10个帖子,我可以做类似的事情:

SELECT * FROM post_type1 ORDER BY time DESC LIMIT 10

但是,如果我想获得最后10个帖子,无论他们属于哪个4个表。

一个想法进入了我的脑海,这是非常低效的,从每个表中获取10条记录(总共40条记录),然后使用php应用合并排序并获得前10条记录。 有没有有效的方法来做到这一点?我真的很喜欢这个。提前谢谢。

2 个答案:

答案 0 :(得分:0)

使用UNION组合它们。由于它们具有不同的列,因此您需要在子查询中为缺少的列添加占位符。

SELECT *
FROM (
    SELECT "post_type1" AS tablename, id, time, col1, col2, NULL AS col3, col4, col5
    FROM post_type1
    ORDER BY time DESC LIMIT 10
    UNION
    SELECT "post_type2" AS tablename, id, time, col1, NULL, col3, col4, NULL
    FROM post_type2
    ORDER BY time DESC LIMIT 10
    UNION
    SELECT "post_type3" AS tablename, id, time, NULL, col2, col3, col4, col5
    FROM post_type3
    ORDER BY time DESC LIMIT 10
    UNION
    SELECT "post_type4" AS tablename, id, time, col1, col2, col3, NULL, NULL
    FROM post_type4
    ORDER BY time DESC LIMIT 10    
)
ORDER BY time DESC
LIMIT 10

确保所有表都在time列上有索引:

ALTER TABLE post_type1 ADD INDEX (time)

答案 1 :(得分:0)

为什么选择10个用户?我认为合并也不是一个好主意。我认为使用UNION是很好的,因为@Barmar写了并将结果放到数组中。然后你可以用数组做你想做的事。