mysql - 合并 1 列并选择其他

标签 mysql sql union aggregate-functions

我有两张表,一张叫“pinned”,一张叫“unread”

“固定”看起来像这样:

+---------+-------+
|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,但在实际实现中会有所不同。我们的想法是 where unread_by=2 和 where pinned_by=2 将以某种方式包含在内。

谢谢

最佳答案

假设有一个 Posts 表,你可以这样做:

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

关于mysql - 合并 1 列并选择其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5112571/

相关文章:

java - 连接超时 : connect JAVA and Wampserver

php - 现在允许使用 CakePHP 中的插件 Authake 执行操作

c# - SQL行没有被删除

MYSQL:联合运算符添加 'total' 行

postgresql - 在 postgres 中使用 union 从 Union 两个表创建一个新表

php - 考虑实现用户积分商店系统

sql - 删除...从...在哪里...在

mysql - 如何在mySQL中将文本列值从一行复制到另一行

tsql - T-SQL UNION在3个表上?

python - 在 DJANGO CRUD 数据库应用程序中创建父/主条目然后将关联数据字段添加到父/主条目的最佳方法是什么?