我是ms sql的初学者,我有两张桌子 第一张表有
id param1 indicator1 indicator2
1 a 1 2
2 z 3 4
2 z 7 2
3 a 8 9
4 z 7 9
5 y 9 6
第二张表有
Param Indicator
a 1
b 2
null 3
null 4
我想要一个可以实现此目的的结果集:
For each row in table 1
if( param1 is in Param column)
print row from table 1
else
if(indicator1 in indicator column_
print row from table 1
if(indicator2 in indicator column)
print row from table 1
因此得到的数据集将是
id param1 indicator1 indicator2
1 a 1 2
2 z 3 4
2 z 7 2
3 a 8 9
我想要一个更有效的解决方案
select distinct id, param1, indicator1, indicator2
from table1 t1, table2 t2
where param1= param or indicator1 = indicator or indicator2 = indicator
答案 0 :(得分:1)
而不是Join
来检查是否存在使用性能更好的EXISTS
。
SELECT *
FROM table1 t
WHERE EXISTS (SELECT 1
FROM table2 s
WHERE t.param1 = s.Param
OR t.indicator1 = s.Indicator
OR t.indicator2 = s.Indicator)
答案 1 :(得分:0)
使用 JOIN 代替逗号分隔的表:
SELECT DISTINCT Id, param1, indicator1, indicator2
FROM table1 t1
JOIN table2 t2 ON t1.param1 = t2.Param OR
t1.indicator1 = t2.indicator OR
t1.indicator2 = t2.indicator
<强>输出:强>
id param1 indicator1 indicator2
1 a 1 2
2 z 3 4
2 z 7 2
3 a 8 9
<强> SQL FIDDLE 强>
答案 2 :(得分:-1)
SELECT * FROM TABLE1 tbl1 INNER JOIN TABLE2 tbl2 on tbl1.param1 = tbl2.param
答案 3 :(得分:-1)
SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.indicator