Mysql从不同的表中添加列

时间:2014-08-10 20:36:01

标签: mysql sql

我有两张桌子:

| USER |
| _id  | - int id PK
| id   | - String id
| name |

| SUBSCRIBE |
|   user    |
| subscribe |

我想提取这些数据:

| _id | id | name | subscribe

简单示例

| USER |
|  1   | 10212551 | Mike
|  2   | 21022145 | Nick

| SUBSCRIBE |
|    1      |     2


get_info($user, $sub );

| EXPECTED RESULT |
|     $user       |  id  |  name  |  0 or 1 (false or true, if $sub has subscribed to $user)

我最好的尝试是使用count():

SELECT u._id,u.id,u.name,u.email,u.country,count(s.subscribe) AS subscribe 
FROM user u,subscribe s 
WHERE u._id='$user' AND s.subscribe='$user' AND s.user='$sub'

但这只有在订阅表中有任何记录时才有效。

的get_info(2,1)

它会给出正确的结果,但是:

的get_info(1,2)

什么都没有:/

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

使用左连接以便返回用户,即使他尚未订阅并使用案例来检查订阅

select u._id,u.id,u.name,u.email,u.country,
case when s.subscribe is not null then 1 else 0 end as subscribe 
from user u 
left join subscribe s on (u._id = s.user and s.subscribe ='$sub')
where u._id='$user' 

Demo