我不确定标题是否清楚,但情况就是这样。
我有一个看起来像这样的表:
ID inputID value
4 1 10
4 2 20
4 3 100
6 1 15
6 2 20
6 3 44
我有用户输入,它为我提供inputID 1和inputID 2的值,之后我想获取ID以获取与该ID相对应的其他信息。
示例:如果用户给出inputID(1)= 10,inputID(2)= 20,我想得到4
使用简单的AND语句无法解决此问题。我问过已经问了几个人,但我似乎无法解决这个看似简单的问题。
答案 0 :(得分:4)
这样的事情怎么样?
SELECT t1.ID
FROM table t1
INNER JOIN table t2
ON t1.ID = t2.ID
WHERE
t1.inputID = 1 AND t1.value = @input1 AND
t2.inputID = 2 AND t2.value = @input2
答案 1 :(得分:1)
select ID from T as T1
where inputID=1 and value=10
and EXISTS(select id from T where ID=T1.ID and inputID=2 and value=20)
答案 2 :(得分:0)
尝试此查询:
Create Table #tmp ( Id int, inputId int, value int)
insert into #tmp values (4,1,10)
insert into #tmp values (4,2,20)
insert into #tmp values (4,3,100)
insert into #tmp values (6,1,15)
insert into #tmp values (6,2,20)
insert into #tmp values (6,3,44)
-- my query
Select top 1 id from
(Select id,count(id) as cnt from #tmp where (inputId=1 and value=10) OR (inputId=2 and value=20) Group by id) tbl
order by cnt desc
-- Scoregraphic's query
SELECT t1.ID
FROM #tmp t1
INNER JOIN #tmp t2
ON t1.ID = t2.ID
WHERE
t1.inputID = 1 AND t1.value = 10 AND
t2.inputID = 2 AND t2.value = 20
Drop table #tmp
在查看执行计划时,我的查询总体上占23%,而ScoreGraphic的查询占用了21%