简体   繁体   English

多个SELECT FROM multi table和SORT按日期

[英]multiple SELECT FROM multi tables and SORT by date

I am looking a way to select multi data from multi tables WHERE uid = :uid and sort them by data . 我正在寻找一种从多个表WHERE uid = :uid选择多个数据sort data对其进行sortdata

some thing like this : 像这样的东西:

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

Actually, in a profile timeline I need to show likes , comments , photos and ... And all of these parts should be sort by date with limitation ... 实际上,在个人资料时间表中,我需要显示likescommentsphotos和...,所有这些部分都应按sort by datelimitation ...

EDIT : 编辑:

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

I need some of every table column but they are not same to use UNION . 我需要每个表列中的一些,但使用UNION并不相同。

Thanks . 谢谢 。

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

This solution requires that the columns from each tables are of same type, the resultset will take the columns names of the first table. 此解决方案要求每个表中的列具有相同的类型,结果集将采用第一个表的列名称。 If only one or two columns differs on each table, you can just extract the similar columns by naming them instead of extracting all columns : http://dev.mysql.com/doc/refman/5.7/en/union.html 如果每个表上只有一两列不同,则可以通过命名相似的列来提取它们,而不是提取所有列: http : //dev.mysql.com/doc/refman/5.7/en/union.html

Extracting all columns with * is usually frowned on, because your code become unreadble without knowledge of the database. 通常不赞成使用*提取所有列,因为如果不了解数据库,您的代码将变得无法读取。 And it might extract more data than needed. 而且它可能会提取比所需更多的数据。

With your data structure you might want to try this (I guessed the column type, so correct it if needed) : 对于您的数据结构,您可能想尝试一下(我猜到了列类型,因此请根据需要更正):

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

I added a type column so it is easier to deal with in php after (you just test this field with a switch case instead of testing if address == 'none' or cid == -1 ...). 我添加了一个type列,以便以后在php中更轻松地进行处理(您只需使用开关案例测试该字段,而不是测试address =='none'或cid == -1 ...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM