実例: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
が、これはクエリがどのように機能するかを示しています。