我有下表:
+-------+-------+-------------+
|column1|column2| column3 |
+-------+-------+-------------+
| 2 | 4 | row 1 | < compare with this
| 4 | 3 | row 2 | + < here`s 4
| 5 | 2 | row 3 | + < here`s 2
| 1 | NULL | row 4 | - < no 4 or 2
| 5 | 6 | row 5 | - < no 4 or 2
| NULL | 2 | row 6 | + < here`s 2
+-------+-------+-------------+
问题是如何查找包含至少一个搜索值的所有行。例如,我需要找到第一行,所以我在前两列中寻找2或4行。所以我的输出应该是2,3和6行。我不需要找到NULL值。
请指教。
答案 0 :(得分:1)
select *
from foo
where ( 2 in (col1, col2)
or 4 in (col1, col2))
and (col3 <> 'row 1')
SQL小提琴示例:http://sqlfiddle.com/#!2/7fd81/5
另外,为了更加动态地获取它:
select t.*
from foo t
join (
select col1, col2
from foo
where col3 = 'row 1'
) r1 on r1.col1 = t.col1
or r1.col2 = t.col2
or r1.col1 = t.col2
or r1.col2 = t.col1
where col3 <> 'row 1'
SQLFiddle:http://sqlfiddle.com/#!2/7fd81/3