2015-09-28 70 views
0

用戶表MySQL同一列中的多個WHERE?

------------------------ 
id  | name 
------------------------ 
1   | Bob Smith 
2   | Jane Doe 
3   | Fred Flintstone 
4   | Barney Rubble 
5   | Marge Simpson 
...  | ... 

連接

----------------------------------------------- 
connection1 | connection2 | connector 
------------------------------------------------ 
1   | 3    | 7 
11   | 5    | 7 
35   | 7    | 7 
18   | 9    | 7 
12   | 13   | 6 
...   | ...   | ... 

以上是表我有一個MySQL數據庫的例子。我知道我可以使用WHERE子句返回一個用戶ID,但我想解析來自同一個用戶表的所有ID。是否有任何優雅的解決方案在一個MySQL語句中返回用戶名?

基本上返回表是這樣的:

----------------------------------------------- 
connection1 | connection2 | connector 
------------------------------------------------ 
Tim   | Steven  | Charlie 
+2

是的,他們是所謂的加入 –

回答

0

爲了做你正在嘗試做的,你需要加入用戶表多次(每個連接)。像下面這樣的東西應該做你想做的事情。

SELECT 
    t1.name as 'connection1', 
    t2.name as 'connection2', 
    t3.name as 'connection3' 
FROM connections c 
JOIN user t1 on t1.id = c.connection1 
JOIN user t2 on t2.id = c.connection2 
JOIN user t3 on t3.id = c.connection3 
+0

這似乎工作!非常感謝你! – Onitsoga

0

SQL 101使用聯接:

SELECT 
    c1.name AS connection1_name, 
    c2.name AS connection2_name, 
    connector 
FROM Connections cn 
JOIN users c1 ON c1.Id = cn.connection1 
JOIN users c2 ON c2.Id = cn.connection2