联盟1列并选择其他

时间:2011-02-25 01:20:04

标签: mysql sql union aggregate-functions

我有两张桌子,一张名为“固定”,另一张名为“未读”

“固定”看起来像这样:

+---------+-------+
|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,真/假等。只要我可以区分哪个post_id来自未读,哪个被固定,哪个来了,我就不在乎了。来自两者。我正在使用MySQL。在这个例子中,_by列都有2个,但在实际实现中会有所不同。想到的是,unread_by = 2,其中pinned_by = 2将以某种方式包含在内。

由于

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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