工作例如:http://sqlfiddle.com/#!2/f1fdd/9
構建模式:
CREATE TABLE user(
id int(11),
name varchar(50)
);
CREATE TABLE userFriends(
userID int(11),
friendID int(11)
);
CREATE TABLE beer(
beerID int(11),
beerName varchar(50)
);
CREATE TABLE friendBeer(
userID int(11),
beerID int(11)
);
INSERT INTO user(id,name) VALUES(1,'friend 1');
INSERT INTO user(id,name) VALUES(2,'friend 2');
INSERT INTO user(id,name) VALUES(3,'friend 3');
INSERT INTO user(id,name) VALUES(4,'jeremy');
INSERT INTO userFriends(userID,friendID) VALUES(4,1);
INSERT INTO userFriends(userID,friendID) VALUES(4,2);
INSERT INTO userFriends(userID,friendID) VALUES(4,3);
INSERT INTO beer(beerID, beerName) VALUES(1, 'amstel light');
INSERT INTO beer(beerID, beerName) VALUES(2, 'bud light');
INSERT INTO beer(beerID, beerName) VALUES(3, 'miller');
INSERT INTO friendBeer(userID, beerID) VALUES(1, 1);
INSERT INTO friendBeer(userID, beerID) VALUES(2, 2);
INSERT INTO friendBeer(userID, beerID) VALUES(3, 3);
INSERT INTO friendBeer(userID, beerID) VALUES(4, 1);
INSERT INTO friendBeer(userID, beerID) VALUES(1, 3);
和查詢:
SELECT U.id,
U.name,
(SELECT count(beerID)
FROM friendBeer
WHERE userID = 4) AS "user beer count",
U2.name AS 'Friends name',
COUNT(FB2.beerID)
FROM user U
LEFT JOIN userFriends F
ON U.id = F.userID
LEFT JOIN user U2
ON F.friendID = U2.id
LEFT JOIN friendBeer FB2
ON F.friendID = FB2.userID
LEFT JOIN friendBeer FB
ON U.id = FB.userID
WHERE U.id = 4
GROUP BY F.friendID, U.id
我假設你會改變=1
對什麼UserID
是 - 但這節目你如何查詢工作。
朋友有他們的id或只是與userid相關的名字嗎? – peterm 2013-03-24 03:26:47
只是他們的名字,我需要他們從用戶表中獲得他們的ID來從啤酒桌獲得他們的啤酒數量,因爲它只有他們的ID – Mike 2013-03-24 03:30:48
那麼你需要一種方法將朋友與用戶聯繫起來,因爲現在如果我將朋友標識添加到朋友表中,您的模式中沒有 – peterm 2013-03-24 03:32:18