2017-01-10 81 views
-3

我的數據庫表「用戶」同一個數據有以下詳細介紹如何選擇數據庫

--------------------------------------- 
id | username | ref | email 
--------------------------------------- 
1 | name1  | 0  | [email protected] 
2 | name2  | 0  | [email protected] 
3 | name3  | 0  | [email protected] 
4 | name4  | 3  | [email protected] 
5 | name5  | 3  | [email protected] 
6 | name5  | 3  | [email protected] 
--------------------------------------- 

這意味着ID 3是4,5,6 引薦我的問題是如何選擇的ID名稱4,5 & 6使用ID 3

+1

'選擇用戶名FROM用戶WHERE ref = 3'? – David

+1

兩個用戶擁有相同的用戶名,並且全部共享相同的電子郵件地址。這會變得相當混亂。 – Strawberry

回答

0

爲什麼你不能使用普通的WHERE條款像

select username from tbl where ref=3; 

如果你需要一個上市的用戶名,然後考慮使用group_concat()group by裁判列

select group_concat(username) 
from tbl1 
group by ref; 

對我來說,看起來你想要的東西,像下面這等於說where ref = 3

select id, username 
from tbl1 
where id in (select distinct id from tbl1 where ref = 3); 
1

使用自連接

select u1.*, u2.username as ref_name 
from user u1 
left join user u2 on u1.ref = u2.id 
+0

這種情況'u1.ref = u2.id'永遠不會匹配 – Rahul

+1

@Rahul爲什麼不呢? – GurV

0
select * from user u1 
left join user u2 on u2.ref = u1.id 
where u1.id = 3