2011-02-25 81 views
1

我有兩個表,一個叫「固定」和一個叫「未讀」聯盟1列,並選擇附加

「固定」是這樣的:

+---------+-------+ 
|pinned_by|post_id| 
+---------+-------+ 
|2  |3  | 
+---------+-------+ 
|2  |5  | 
+---------+-------+ 

「未讀」看起來是這樣的:

+---------+-------+ 
|unread_by|post_id| 
+---------+-------+ 
|2  |5  | 
+---------+-------+ 
|2  |10  | 
+---------+-------+ 

我想從兩個表中選擇的:

+-------+------+------+ 
|post_id|unread|pinned| 
+-------+------+------+ 
|3  |0  |1  | 
+-------+------+------+ 
|5  |1  |1  | 
+-------+------+------+ 
|10  |1  |0  | 
+-------+------+------+ 

我該怎麼做?通過固定和未讀取的值可能是1/0,1/null,true/false等。我並不在乎,只要我能區分哪些post_id來自未讀,哪些是固定的,哪些來的來自兩者。我正在使用MySQL。 _by列在這個例子中都有2個,但在實際實現中會有所不同。想到的是,其中unread_by = 2和其中pinned_by = 2將以某種方式包含在內。

感謝

+0

是否有職位表POST_ID值的一個列表? – 2011-02-25 02:11:33

+0

是的,我應該包括那個對不起 – Colin 2011-02-25 02:15:58

回答

0

。假定有帖子的表,你可以這樣做:

Select P.post_Id 
    , Max(Case When UR.unread_by Is Not Null Then 1 Else 0 End) As unread 
    , Max(Case When P2.pinned_by Is Not Null Then 1 Else 0 End) As pinned 
From Posts As P 
    Left Join Unread As UR 
     On UR.post_Id = P.post_Id 
    Left Join Pinned As P2 
     On P2.post_id = P.post_id 
Group By P.post_id 
+0

非常優雅......我將你的Max()切換到最小(1,UR.unread_by)以返回1或null,但差別可能可以忽略不計。我這樣做是因爲我認爲Scrum Meister的子查詢方法會更快,但是如果這是一個糟糕的評估,那麼每個人都可以自由地插話。 – Colin 2011-02-25 02:10:40

0

您可以使用UNION

SELECT post_id, SUM(PinCount), SUM(UnreadCount) 
FROM (
    SELECT post_id, COUNT(*) PinCount, 0 UnreadCount 
    FROM pinned 
    GROUP BY post_id 
    UNION ALL SELECT post_id, 0, COUNT(*) UnreadCount 
    FROM unread 
    GROUP BY post_id 
) 
GROUP BY post_id 

或者,如果你有一個post表持有所有的職位,您可以使用表 - 因爲MySQL沒有一個完整的外連接。

SELECT t.post_id, p.PinCount, u.UnreadCount 
FROM posts t LEFT JOIN (
    SELECT post_id, COUNT(*) PinCount 
    FROM pinned 
    GROUP BY post_id 
) p USING(post_id) 
    LEFT JOIN (
    SELECT post_id, COUNT(*) UnreadCount 
    FROM unread 
    GROUP BY post_id 
) u USING(post_id) 
GROUP BY t.post_id 
+0

對於第二個例子,在最後一行之前還有一個額外的「)」。另外,如果posts.post_id是主鍵,而在其他兩個表中,兩列都在主鍵中,那麼是否需要最後一個GROUP BY? – Colin 2011-02-25 01:55:42

+0

@colin固定。是的,如果它是主鍵,則可以省略最後的「GROUP BY」。 – 2011-02-25 02:00:06

0
SELECT COALESCE(pinned.post_id,unread_post_id) AS postid, unread_by, pinned_by 
FROM pinned OUTER JOIN unread ON pinned.post_id = unread.post_id 
0

用途:

SELECT x.post_id, 
      COUNT(u.unread_by) AS unread, 
      COUNT(x.pinned_by) AS pinned 
    FROM (SELECT p.post_id 
      FROM PINNED p 
      UNION 
      SELECT u.post_id 
      FROM UNREAD u) x 
LEFT JOIN UNREAD u ON u.post_id = x.post_id 
LEFT JOIN PINNED p ON p.post_id = x.post_id 
GROUP BY x.post_id