Mysql Union 1列并选择“附加”

Mysql Union 1列并选择“附加”,mysql,sql,union,aggregate-functions,Mysql,Sql,Union,Aggregate Functions,我有两张桌子,一张叫“钉住”,一张叫“未读” 看起来像这样: +---------+-------+ |pinned_by|post_id| +---------+-------+ |2 |3 | +---------+-------+ |2 |5 | +---------+-------+ +---------+-------+ |unread_by|post_id| +---------+-------+ |2 |5

我有两张桌子,一张叫“钉住”,一张叫“未读”

看起来像这样:

+---------+-------+
|pinned_by|post_id|
+---------+-------+
|2        |3      |
+---------+-------+
|2        |5      |
+---------+-------+
+---------+-------+
|unread_by|post_id|
+---------+-------+
|2        |5      |
+---------+-------+
|2        |10     |
+---------+-------+
“未读”看起来像这样:

+---------+-------+
|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、真/假等。只要我能区分哪些帖子id来自未读、哪些被固定以及哪些来自这两者,我就不在乎了。我正在使用MySQL。在本例中,_by列都有2个,但在实际实现中会有所不同。其思想是,一个where-unread_by=2和where-pinted_by=2将以某种方式包括在内

谢谢

您可以使用工会:

或者,如果您有一个包含所有post的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
使用:


假设有一个帖子表,您可以执行以下操作:

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

对于第二个示例,在最后一行之前有一个额外的字符。另外,如果posts.post_id是主键,并且在其他两个表中,两列都在主键中,那么我是否需要最后一个GROUP BY?@colin Fixed。是的,如果它是主键,你可以省略最后一组。非常优雅…我将你的最大值切换为Least1,UR.unread_BY以返回1或null,但差异可能可以忽略不计。我之所以这么做,是因为我认为它比Scrum Meister的子查询方法更快,但是如果这是一个糟糕的评估,每个人都可以随意插话。是否有一个POSTS表来列出post_id值?是的,我应该包括这个,对不起
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