我需要返回以下所有值:select ... where IN(1,2,3,3,1,1)
我有一张包含唯一ID的表格。我有以下查询:
Select * From Table_1 Where ID IN (1,2,3,3,3,1);
到目前为止,我只返回3条唯一值(1,2,3)的记录
我想要返回6条记录。
我需要在图片上显示结果集。
答案 0 :(得分:1)
您无法使用IN
运算符执行此操作。您可以创建一个临时表并加入:
CREATE TABLE #TempIDs
(
ID int
)
INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (2)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (1)
Select Table_1.* From Table_1
INNER JOIN #TempIDs t n Table_1.ID = t.ID;
另一个(可能更丑陋)的选择是做UNION
:
Select * From Table_1 Where ID = 1
UNION ALL
Select * From Table_1 Where ID = 2
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 1
答案 1 :(得分:0)
您无法使用IN
条件执行此操作,因为IN
会将您的商品视为一组(即确保唯一性)。
您可以通过加入UNION ALL
来生成所需的结果,如下所示:
SELECT t.*
FROM Table_1 t
JOIN ( -- This is your "IN" list
SELECT 1 AS ID
UNION ALL SELECT 2 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 1 AS ID
) x ON x.ID = t.ID
答案 2 :(得分:0)
你可以做到。但不是IN。
Select
src.*
From Table_1 src
inner join (
select
ID,
myorder
from (values
(1,0),
(2,1),
(3,2),
(3,3),
(3,4),
(1,5)
) x (ID,myorder)
) T ON
T.ID = src.ID
order by T.myorder
请记住,如果您需要数据集,请订购,您必须提供order by子句。