如何合并两个sql选择

时间:2016-07-08 03:38:53

标签: sql merge

我想合并一个表中的两个SQL选择

查询1:

SELECT UserId
FROM ShoppingLike
WHERE (ShoppingScoreTypeId = 2) AND (WhichId = 75)

查询2:

SELECT ShoppingLike.WhichId
FROM ShoppingLike
WHERE (ShoppingLike.ShoppingScoreTypeId = 2) AND (ShoppingLike.UserId = 189)

而不是查询1中的75,我应该如何使用查询2的结果?

2 个答案:

答案 0 :(得分:0)

SELECT        UserId
FROM            ShoppingLike
WHERE        (ShoppingScoreTypeId = 2)
AND WhichId = (
 SELECT        top 1 ShoppingLike.WhichId
 FROM            ShoppingLike
 WHERE        (ShoppingLike.ShoppingScoreTypeId = 2) AND (ShoppingLike.UserId = 189)
)

答案 1 :(得分:0)

可能有子选择查询吗?

SELECT UserId
FROM ShoppingLike
WHERE WhichId IN (
    SELECT WhichId
    FROM ShoppingLike
    WHERE (ShoppingScoreTypeId = 2) AND (UserId = 189)
)

虽然这总会产生UserId 189行,但在这种情况下,查询可以简单地写成:

SELECT UserId
FROM ShoppingLike
WHERE (ShoppingScoreTypeId = 2) AND (UserId = 189)

这会为ShoppingScoreTypeId = 2的UserId = 2的每条记录返回一行。