如何在where子句后使用左连接

时间:2015-08-09 13:02:07

标签: mysql

我有两张桌子:

// comment 
+----+---------+---------+----------------------+
| id | id_post | user_id |       content        |
+----+---------+---------+----------------------+
| 1  |  1111   |  2222   |   this is content1   |
| 2  |  3333   |  2222   |   this is content2   |
| 3  |  3333   |  4444   |   this is content3   |
+----+---------+---------+----------------------+

// user
+------+-----------+
|  id  |   name    |
+------+-----------+
| 2222 |   jack    |
| 4444 |   peter   |
+------+-----------+

这是我的疑问:

select c.content, u.name
  from comment c inner join user u on c.id_user = u.id
  where c.id_post = 3333;

这是我的结果:

+----------------------+-----------+
|        content       |   name    |
+----------------------+-----------+
|   this is content2   |   jack    |
|   this is content3   |   peter   |
+----------------------+-----------+

所以,我的问题:我需要添加一个包含1数字的列,但仅针对特定用户。换句话说,我想要这个输出

// for this user: 2222 (or jack)
+----------------------+-----------+----------+
|        content       |   name    | user_id  |
+----------------------+-----------+----------|
|   this is content2   |   jack    |    1     |
|   this is content3   |   peter   |          |
+----------------------+-----------+----------+

// for this user: 444  (or peter)
+----------------------+-----------+----------+
|        content       |   name    | user_id  |
+----------------------+-----------+----------|
|   this is content2   |   jack    |          |
|   this is content3   |   peter   |     1    |
+----------------------+-----------+----------+

我想我应该再使用一个left join,但我不知道如何在查询中添加一个left join。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我认为您只需要flag中的select

select c.content, u.name,
       (u.id = 222) as hasUserId
from comment c inner join
    user u
    on c.id_user = u.id
where c.id_post = 3333;

我应该注意:上面的返回1或0.如果你想要1或NULL

select c.content, u.name,
       (case when u.id = 222 then 1 end) as hasUserId