2015-02-09 70 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