[英]Select by pair of fields in MySQL
我有下表:
+-------+-------+-------------+
|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值。
请指教。
select *
from foo
where ( 2 in (col1, col2)
or 4 in (col1, col2))
and (col3 <> 'row 1')
SQL Fiddle示例: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.