2016-03-28 60 views
0

我必須根據朋友表中使用JOIN中的數據顯示每對朋友的名稱。 My output should come exactly like this 我附上下面如何在SQL中使用多重連接顯示值

在這裏,我的預期結果圖像是我的代碼:

CREATE TABLE persons (
id INTEGER PRIMARY KEY AUTOINCREMENT, 
fullname TEXT, 
age INTEGER); 

INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); 
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); 
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); 
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); 
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); 

CREATE table hobbies (
id INTEGER PRIMARY KEY AUTOINCREMENT, 
person_id INTEGER, 
name TEXT); 

INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); 
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); 
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); 
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); 
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); 
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); 
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); 
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); 
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); 
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); 

CREATE table friends (
id INTEGER PRIMARY KEY AUTOINCREMENT, 
person1_id INTEGER, 
person2_id INTEGER); 

INSERT INTO friends (person1_id, person2_id) 
VALUES (1, 4); 
INSERT INTO friends (person1_id, person2_id) 
VALUES (2, 3); 

回答

1

所以你基本上需要一個INNER JOIN

SELECT t.fullname,s.fullname 
FROM persons t 
INNER JOIN friends f 
ON(t.id = f.person1_id) 
INNER JOIN persons s 
ON(f.person2_id = s.id) 
0

MySQL查詢

SELECT p1.fullname, p2.fullname 
FROM friends f 
JOIN persons p1 on f.person1_id = p1.id 
JOIN persons p2 on f.person2_id = p2.id