合并 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,但在实际实现中会有所不同。我们的想法是, where unread_by=2 和 where pinned_by=2 将以某种方式包含在内。
谢谢
I have two tables, one called "pinned" and one called "unread"
"pinned" looks like this:
+---------+-------+
|pinned_by|post_id|
+---------+-------+
|2 |3 |
+---------+-------+
|2 |5 |
+---------+-------+
"unread" looks like this:
+---------+-------+
|unread_by|post_id|
+---------+-------+
|2 |5 |
+---------+-------+
|2 |10 |
+---------+-------+
I want to select this from the two tables:
+-------+------+------+
|post_id|unread|pinned|
+-------+------+------+
|3 |0 |1 |
+-------+------+------+
|5 |1 |1 |
+-------+------+------+
|10 |1 |0 |
+-------+------+------+
How can I do this? The values that come through for pinned and unread could be 1/0, 1/null, true/false, etc. I don't really care as long as I could differentiate which post_id's came from unread, which came pinned, and which came from both. I'm using MySQL. The _by columns all have 2 in this example, but will vary in the actual implementation. The thought is that a where unread_by=2 and where pinned_by=2 will be included somehow.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设有一个 Posts 表,你可以这样做:
Presuming that there is a table of Posts, you can do:
使用:
Use:
您可以使用
UNION
:或者,如果您有一个包含所有帖子的
post
表,您可以使用该表 - 因为 MySql 没有完整的外连接。You can use a
UNION
:Or, if you have a
post
table which holds all the posts, you can use that table - since MySql doesn't have a full outer join.