多个SELECT FROM多表和按日期排序

时间:2016-03-26 05:48:48

标签: php mysql database union

我正在寻找一种从多表WHERE uid = :uid中选择多数据的方法 sort data {。}}。{/ p>

有些事情是这样的:

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 {{1} } ...

编辑:

limitation

我需要一些每个表列,但它们使用UNION不一样。

谢谢。

1 个答案:

答案 0 :(得分:3)

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之后更容易处理(您只需使用switch case测试此字段,而不是测试address =='none'或cid == -1 ...)。 / p>