SQL交叉匹配来自不同列和行的数据

时间:2015-02-09 23:12:08

标签: mysql sql

我一直很难搞清楚如何选择以下内容......

我有两张桌子

Table_users                      Table_followers
| id | name     |                | follow_id | user_id |
| 1  | John     |                | 1         | 2       |
| 2  | Max      |                | 3         | 1       |
| 3  | Mary     |                | 2         | 1       |
| 4  | Robert   |                | 6         | 1       |
| 5  | Robin    |                | 1         | 5       |
| 6  | Sarah    |                | 1         | 6       |
  1. 我想在单个查询中返回跟随John和John的用户正在关注它们,因此称为MATCH。
  2. 然后关注John,FOLLOWERS
  3. 的用户
  4. 最后用户跟着John,关注
  5. 我使用了以下查询,但它返回了重复内容,并且远非我正在寻找的内容

    SELECT u.id, u.name, f.follower_id, f.user_id
    FROM table_users u
    LEFT JOIN table_followers f ON f.follower_id = u.id OR f.user_id = u.id
    WHERE (f.user_id != 1 OR f.follower_id != 1) AND u.id != 1
    ORDER BY u.id ASC";
    

    期望的结果就像......

    | uid | name     | match | follower | following |
    | 2   | Max      | 1     | null     | null      |
    | 6   | Sarah    | 1     | null     | null      |
    | 3   | Mary     | null  | 1        | null      |
    | 5   | Robin    | null  | null     | 1         |
    

    是否可以使用SQL?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是将关注者表加入两次(一次关注关注者,一次关注关注)并执行以下查询:

select 
    u.id,
    u.name, 
    case when follow_id and user_id then 1 end as `match`,
    case when follow_id and user_id is null then 1 end as follower,
    case when user_id and follow_id is null then 1 end as following
from Table_users u
left join (select user_id from Table_followers where follow_id = 1) followers 
    on u.id = followers.user_id
left join (select follow_id from Table_followers where user_id = 1) following 
    on u.id = following.follow_id
where u.id <> 1 and (follow_id or user_id)
order by `match` desc, follower desc, following desc, u.id;

我确信有更有效和更清洁的方法可以做到这一点,但现在已经很晚了,老脑只能以半速运转;)

Sample SQL Fiddle

使用MySQL,选择部分可以进一步简化为:

select 
    u.id,
    u.name, 
    ifnull((follow_id and user_id),0) as `match`,
    (follow_id and user_id is null) as follower,
    (user_id and follow_id is null) as following
from Table_users u

但是对于缺失值,这会给你0而不是null。 (Sample)。