多个从多个表中选择并按日期排序


multiple SELECT FROM multi tables and SORT by date

我正在寻找一种从多表中选择多数据的方法WHERE uid = :uid并通过data sort它们.

像这样的事情:

SELECT * FROM
    (SELECT * from comments) AND
    (SELECT * from likes) AND
    (SELECT * from photos) AND
    (SELECT * from messages) WHERE uid = :uid ORDER BY date LIMIT 30

实际上,在个人资料时间轴中,我需要显示likescommentsphotos和...所有这些部分都应该sort by date limitation......

编辑:

Select cid,comment,pid,date from `ctg_comments` where uid = 69
UNION
Select pid,date from `ctg_likes` where uid = 69
UNION
Select address,postid,date from `ctg_photos` where byuid = 69
UNION
Select postid,date from `ctg_reservation` where uid=69
Order by date limit 30

我需要每个表列中的一些,但它们与使用 UNION 不同。

谢谢。

Select * from comments where uid=:uid
UNION
Select * from likes where uid:uid
UNION
Select * from photos where uid:uid
UNION
Select * from messages where uid:uid
Order by date limit 30

此解决方案要求每个表中的列具有相同的类型,结果集将采用第一个表的列名。如果每个表上只有一个或两个列不同,则可以通过命名来提取相似的列,而不是提取所有列:http://dev.mysql.com/doc/refman/5.7/en/union.html

提取带有 * 的所有列通常是不受欢迎的,因为您的代码在不知道数据库的情况下变得不可读。它可能会提取比需要的更多的数据。

对于您的数据结构,您可能想尝试一下(我猜了列类型,因此如果需要,请更正(:

Select 'comment' as type, 'none' as address, cid, comment, pid, date from `ctg_comments` where uid = 69
UNION
Select 'like' as type, 'none' as address, -1 as cid, 'none' as comment, pid, date from `ctg_likes` where uid = 69
UNION
Select 'photo'as type, address, -1 as cid, postid as pid, 'none' as comment, date from `ctg_photos` where byuid = 69
UNION
Select 'reservation' as type, 'none' as address, -1 as cid, postid as pid, 'none' as comment, date from `ctg_reservation` where uid=69
Order by date limit 30

我添加了一个类型列,以便在 php 之后更容易处理(您只需使用开关大小写测试此字段,而不是测试地址是否 == 'none' 或 cid == -1 ...