我有 2 张 table
主表
Id_post
Id_user_post
Post
Date_post
辅助表
Id_mentioned
Id_user
Id_user_post
Id_post
Date_mentioned
例如,我第一个表有 13 条记录,第二个表有 3 条记录。
第一表记录(13条)
1 herman this is text 1 10:00:00 15/09/2016
2 jhon this is text 2 11:00:00 15/09/2016
3 carl this is text 3 12:00:00 15/09/2016
4 herman this is text 4 13:00:00 15/09/2016
5 herman this is text 5 14:00:00 15/09/2016
6 herman this is text 6 15:00:00 15/09/2016
7 jhon this is text 7 16:00:00 15/09/2016
8 herman this is text 8 17:00:00 15/09/2016
9 herman this is text 9 18:00:00 15/09/2016
10 carl this is text 10 19:00:00 15/09/2016
11 herman this is text 11 20:00:00 15/09/2016
12 carl this is text 12 21:00:00 15/09/2016
13 herman this is text 13 22:00:00 15/09/2016
第二表记录
1 herman jhon 7 11:20:00 15/09/2016
2 jhon carl 10 12:30:00 15/09/2016
3 herman carl 3 14:50:00 15/09/2016
如果我选择赫尔曼的帖子,我想要下一个结果,按日期排序(发布日期和提及日期)
1 herman this is text 1 10:00:00 15/09/2016
7 jhon this is text 7 11:20:00 15/09/20167 (date mentioned)
4 herman this is text 4 13:00:00 15/09/2016
5 herman this is text 5 14:00:00 15/09/2016
3 carl this is text 3 14:50:00 15/09/2016 (date mentioned)
6 herman this is text 6 15:00:00 15/09/2016
8 herman this is text 8 17:00:00 15/09/2016
9 herman this is text 9 18:00:00 15/09/2016
11 herman this is text 11 20:00:00 15/09/2016
13 herman this is text 13 22:00:00 15/09/2016
在这些结果中,出现了 Hermman 提交的帖子和第二个表中提到的帖子,按 date_thought 排序(它类似于 Twitter,在个人资料中,在主要结果中出现了自己的帖子和不属于同一帖子的转发)所有者)
我尝试了 sql join left
Select * from $table_posts left join $table_mentions on $table_posts.id_user=$table_mentions.id_user order by date_post,date_mentioned
我也尝试过,但是没有结果...
SELECT * FROM $table_posts WHERE id_user_post=(SELECT id_user_post FROM $table_mentions WHERE id_user_post='$id_user') AND id_user_post='$id_user' ORDER BY date_post,date_mentioned DESC
最佳答案
首先,如果我正确理解你的设计,你需要规范化你的数据库。正如我所见, Id_post
指的是第一个表中的 id。但是,您还可以使用 User_post
来引用 Id_post
的用户,但这是不必要的。现在,您所描述的并不完全是联接,而是第一个表的并集以及第一个和第二个表的联接。类似于:
SELECT t.Id_Post, t.Id_User, t.Post, t.Date_post FROM (
SELECT a.Id_Post, a.Id_User, a.Post, a.Date_post FROM table_posts a
UNION ALL
SELECT b.Id_Post, b.Id_User, b.Post, c.Date_mentioned as Date_post
FROM table_posts b JOIN table_mentions c ON b.Id_post = c.Id_Post
) t ORDER BY t.Date_post DESC;
关于mysql - Sql 连接按两个日期排序的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39514492/