将多个sql表和多个sql查询合并为一个语句

时间:2013-03-24 02:46:34

标签: php mysql

我已经研究过使用join方法将表连接在一起,但是我不仅想要连接表,还要查询一个语句,而且我不知道如何将查询连接成一个。

我有三张桌子,一张叫朋友,一张叫用户,一张叫做啤酒。

用户表:

名称| ID

朋友表:

userID | FRIENDNAME

啤酒桌:

userID |啤酒

我想找到给定用户的所有朋友,并且查询获得每个用户和朋友所拥有的独特啤酒的数量。

以前我使用php来“构建”sql语句来执行,这在循环中进行了大量的sql调用,而且只是凌乱。我知道必须有一种更有效的方法。

2 个答案:

答案 0 :(得分:1)

工作示例: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的任何内容 - 但这会向您显示查询的工作原理。

答案 1 :(得分:0)

create table user(user_id int(11),user_name varchar(100));
create table friend(user_id int(11),friend_to int(11));
create table beer(user_id int(11),beer_name varchar(100));

insert into user values(1,'Evan');
insert into user values(2,'Mike');
insert into user values(3,'Roxetta');
insert into user values(4,'Rajesh');

insert into friend values(1,2);
insert into friend values(1,3);

insert into beer values(1,'sam bud');
insert into beer values(2,'carlsberg');
insert into beer values(2,'sam bud');
insert into beer values(2,'sam bud');

和sql查询

SELECT user.user_name, COUNT(DISTINCT(beer.beer_name)) `count` FROM beer JOIN `user` ON user.user_id=beer.user_id WHERE user.user_id=1
UNION
SELECT user.user_name,COUNT(DISTINCT(beer.beer_name)) FROM beer JOIN `user` ON user.user_id=beer.user_id 
WHERE user.user_id IN(SELECT friend_to FROM friend WHERE user_id=1);

这是你要找的吗?