multiple SELECT FROM multi tables 和 SORT by date

multiple SELECT FROM multi tables and SORT by date

我正在寻找一种方法 select 来自多个 table 的多个数据 WHERE uid = :uid sort 他们 data.

像这样的东西:

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 datelimitation ...

编辑:

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

我需要每个 table 列中的一些列,但它们与使用 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

此解决方案要求每个 table 中的列的类型相同,结果集将采用第一个 table 的列名。如果每个 table 只有一两列不同,您可以通过命名它们来提取相似的列,而不是提取所有列: 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 测试此字段而不是测试地址 == 'none' 或 cid == -1 ...).