2016-09-15 85 views
0

我有2個表SQL JOIN由兩個日期排序兩個表

主表

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提交的帖子和第二個ta中提到的帖子BLE,通過date_mentioned(其somenthing像Twitter,其中在配置文件中,主要結果顯示在自己的職位,那不屬於同一業主retwitts)

我試過SQL連接左下令

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 
+0

您使用的是日期時間數據類型,對吧?見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry

+0

CURRENT_TIMESTAMP() – masterhoo

+0

第二張桌子與第一張桌子有什麼關係? – apokryfos

回答

0

首先,如果我正確理解你的設計,你需要規範化你的數據庫。正如我所看到的,Id_post引用了第1個表中的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; 
+0

我想這個代碼,但有一個錯誤,它不顯示結果的預期。 – masterhoo

+0

它顯示出什麼樣的結果VS做什麼你期待什麼呢? – apokryfos

+1

有與第二查詢表的別名了次要的東西。再試試吧,讓我知道。 – apokryfos