2015-02-09 69 views
1

我一直有困难的时候搞清楚如何选择以下...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. 我想在单个查询中返回正在关注约翰和约翰的用户关注他们,以便称为MATCH。
  2. 那么谁是下约翰用户,追随者
  3. 最后用户随后约翰,继

我用下面的查询,但它返回重复,它从我要找的是远

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   | 

难道是p用SQL可以吗?要解决这个

回答

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而不是空的缺失值。 (Sample)。

+1

0的更好! – Armand 2015-02-10 00:14:03

+1

@Armand然后,最后一个示例链接应该是你想要的。 :) – jpw 2015-02-10 00:14:41