我有两张表,一张叫“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/