给出下表:
SET VAL1 VAL2
-----------------
1 a a1
1 b b1
1 c c1
2 d d2
2 e e2
是否可以创建一个查询来标识行的子集,该行的子集具有VAL1和VAL2列的特定值以及SET列中的相同值?
与类似的具有2列的示例相反,我们不能在这里使用IN(据我所知),因为VAL1和VAL2值的组合不是任意的,而是给出的。
预期输出为
VAL1 = a and VAL2 = a1 and VAL1 = b and VAL2 = b1 and VAL1 = c and VAL2 = c1 => 1
还有
VAL1 = d and VAL2 = d2 and VAL1 = e and VAL2 = e2 => 2
还有
VAL1 = d and VAL2 = d2 and VAL1 = e and VAL2 = f => null
问题是,我不能使用类似这样的东西:
SELECT SET
FROM MyTable
WHERE VAL1 IN (a, b, c) AND VAL2 IN (a1, b1, c1)
因为它不会尊重特定的行,并且不会对像这样的星座给出错误的肯定:
SET VAL1 VAL2
-----------------
1 c a1
1 a b1
1 b c1
2 e d2
2 d e2
答案 0 :(得分:3)
在MySQL中,IN
can be used to compare row constructors:
WHERE (val1, val2) IN (
('a', 'a1'),
('b', 'b1'),
('c', 'c1')
)
答案 1 :(得分:0)
使用group by
和having
。
select `set`
from tbl
group by `set`
having sum((VAL1 = 'a' and VAL2 = 'a1') or (VAL1 = 'b' and VAL2 = 'b1') or (VAL1 = 'c' and VAL2 = 'c1')) = 3