2014-03-13 51 views
0

我有這樣的兩個表訂單由兩個表日採用聯盟的替代

評論

| ID | COMMENT | FULLNAME  | PHOTO_ID |   CREATED_AT   | 
|----|---------|----------------|----------|---------------------------------| 
| 76 | comment1| John Smith  |  14 | February, 25 2014 10:38:02+0000 | 
| 77 | comment2| James Anderson |  14 | February, 25 2014 10:38:14+0000 | 
| 78 | comment3| Will Smith  |  15 | March, 11 2014 14:24:08+0000 | 

意見

| ID | USER | PID |   CREATED_AT   | 
|----|------------|---------------------------------| 
| 63 | user1| 15 | February, 25 2014 11:12:03+0000 | 
| 64 | user1| 14 | February, 25 2014 11:14:10+0000 | 
| 66 | user2| 15 | February, 25 2014 11:15:16+0000 | 
| 68 | user2| 14 | February, 25 2014 10:38:12+0000 | 

我想從comments.comment獲取值,comments.fullnameviews.user所以我可以將它們用於foreach,結果將按照如下順序排序:

John Smith added a comment February, 25 2014 10:38:12 //comment1 user2 viewed the file February, 25 2014 10:38:12 //view James Anderson added a comment February, 25 2014 10:38:12 //comment2

我使用這個查詢使用UNION,但我不認爲這是正確的做法,因爲我不能使用全名告訴是誰寫的評論或用戶查看文件

SELECT comment, fullname, comments.created_at 
FROM comments 
WHERE comments.photo_id = 14 
UNION 
SELECT user, '', views.created_at 
FROM views 
WHERE views.pid = 14 
ORDER BY created_at DESC 

,其結果是

| COMMENT |  FULLNAME |      CREATED_AT | 
|----------|----------------|---------------------------------| 
| user1 |    | February, 25 2014 11:14:10+0000 | 
| comment2 | James Anderson | February, 25 2014 10:38:14+0000 | 
| user2 |    | February, 25 2014 10:38:12+0000 | 
| comment1 |  John Smith | February, 25 2014 10:38:02+0000 | 

所以,是有另一種方式這兩個表合併,按日期排序他們並分別得到了行? 這是sqlfiddle

+0

這些拖車桌之間的關係是什麼? – KrazzyNefarious

+0

它們之間沒有關係。 – gael

回答

0

不是100%肯定,如果這是你在找什麼,但你可以試試看......

SELECT IF(comment = 'view', 'view', 'comment') AS type, comment, fullname, created_at 
FROM 
(
    SELECT comment, fullname, comments.created_at 
    FROM comments 
    WHERE comments.photo_id = 14 
    UNION 
    SELECT 'view', user, views.created_at 
    FROM views 
    WHERE views.pid = 14 
) tbl 
ORDER BY created_at DESC 

sqlfiddle

+0

每個OP請求..您的選擇應該是這樣的... SELECT全名,IF(評論='查看','查看文件','添加評論')AS類型,created_at,評論 –

+0

@JohnRuddell這是那種我寧願放在顯示代碼中。如果要更改顯示的措辭,則不必更新查詢。所以你會有類似的東西(假設PHP)'echo($ resultRow [「type」] ==「view」?「)查看文件」:「添加了評論」);' –

+0

沒有我對那個問題...我更多的是說明你如何將它拉出來的順序,更簡單的是按照正確的順序拉出它,所以你不必在之後做出這些改變,並且如果你在if()中輸入一個字符串,它已經更簡單了,使得字符串OP想要什麼額外的編碼來改變它......我的正常偏好雖然 –

0

這應該做的伎倆:

SELECT 
    USER, ACTION, TIME 
FROM 
    (
    SELECT 
     FULLNAME as USER 
     ,'COMMENT' as ACTION 
     ,CREATED_AT as TIME 
    FROM comments 
    ) 
    UNION ALL 
    (
    SELECT 
     USER as USER 
     ,'VIEW' as ACTION 
     ,CREATED_AT as TIME 
    FROM views 
    ) 
WHERE 
    VIEWS_PID = 14 
OERDER BY 
    TIME DESC 
+0

你沒有別名對你的表...我不認爲VIEWS_PID會工作,因爲你不會使它的東西 –