我遇到一个问题,需要执行多个查询才能找到结果。如何在一个查询中完成此操作,因为我需要提高性能?
基本上,我需要从表A中选择与给定用户的项目共享表B中的常用行的项目。
从Usertable
中选择人员
如果
1)他们拥有用户已经拥有的任何成果
示例:
罗杰有苹果和橘子。肯尼斯有芒果和苹果。朱莉有芒果。
问题:选择与Roger分享共同成果的人
The Query挑选Kenneth,因为他与Roger共享一个项目(苹果)。
显然,我可以使用3个查询并按照以下步骤完成此操作:
1)选择人员
2)运行每个用户项目的foreach
3)如果用户包含Roger的水果,请选择它们
如何在一个查询中执行此操作?
答案 0 :(得分:1)
没有精确的表结构无法给出正确的答案。但您可以使用'IN'
子句
select * from Usertable a join userfruit b on .....
where b. fruit in ( select fruit from userfruit where username='Roger')
请检查此演示SQLFiidle
答案 1 :(得分:1)
SELECT a.username
FROM Usertable a
JOIN userfruit b
ON a.user_id = b.user_id
WHERE
a.fruit IN (
SELECT b.fruit
FROM userfruit
WHERE username='Roger'
);
答案 2 :(得分:0)
执行如下所示的选择,并在迭代结果时添加到结构Map<UserName, List<Fruits>>
。
select usertable.name, userfruits.fruitname from usertable join userfruits on (usertable.name = userfruits.username) order by usertable.name;
这将为您提供以下类型的结果:
Name |FruitName
----------------------------
Julie |Mangoes
Kenneth |Apple
Kenneth |Mangoes
Roger |Apple
Roger |Orange
答案 3 :(得分:0)
CREATE TABLE #tmpPerson (
Id INT,
Name NVARCHAR(32)
)
CREATE TABLE #tmpFruit (
Id INT,
Name NVARCHAR(32)
)
CREATE TABLE #tmpPersonFruit (
PersonId INT,
FruitId INT
)
INSERT INTO #tmpPerson (Id, Name) VALUES (1, 'Roger')
INSERT INTO #tmpPerson (Id, Name) VALUES (2, 'Kenneth')
INSERT INTO #tmpPerson (Id, Name) VALUES (3, 'Julie')
INSERT INTO #tmpFruit (Id, Name) VALUES (1, 'Apples')
INSERT INTO #tmpFruit (Id, Name) VALUES (2, 'Oranges')
INSERT INTO #tmpFruit (Id, Name) VALUES (3, 'Mangoes')
INSERT INTO #tmpPersonFruit (PersonId, FruitId) VALUES(1, 1)
INSERT INTO #tmpPersonFruit (PersonId, FruitId) VALUES(1, 2)
INSERT INTO #tmpPersonFruit (PersonId, FruitId) VALUES(2, 1)
INSERT INTO #tmpPersonFruit (PersonId, FruitId) VALUES(2, 3)
INSERT INTO #tmpPersonFruit (PersonId, FruitId) VALUES(3, 3)
GO
DECLARE @Person NVARCHAR(64)
SET @Person = 'Roger'
SELECT Person.Name AS PersonName,
Fruit.Name AS FruitName
FROM #tmpPerson AS Person
INNER JOIN #tmpPersonFruit AS PersonFruit
ON Person.Id = PersonFruit.PersonId
INNER JOIN( SELECT F.*
FROM ( SELECT *
FROM #tmpPerson
WHERE Name = @Person) AS P
INNER JOIN #tmpPersonFruit AS PF
ON P.Id = PF.PersonId
INNER JOIN #tmpFruit AS F
ON PF.FruitId = F.Id) AS Fruit
ON PersonFruit.FruitId = Fruit.Id
GO
DROP TABLE #tmpPerson
DROP TABLE #tmpFruit
DROP TABLE #tmpPersonFruit
如果您需要完整解释其原因,请与我们联系。