简体   繁体   中英

SQL query: how to check existence of *multiple* rows and columns with one query

Given the following table:

SET   VAL1   VAL2
-----------------
1      a      a1
1      b      b1    
1      c      c1
2      d      d2
2      e      e2

Is it possible to create a query which identifies a subset of rows with particular values for columns VAL1 and VAL2 and identical values in column SET?

In contrast to the similar example with 2 columns we can not use IN here (as far as I see) because the combinations of VAL1 and VAL2 values are not arbitrary but given.

The expected output would be for

VAL1 = a and VAL2 = a1 and VAL1 = b and VAL2 = b1 and VAL1 = c and VAL2 = c1  => 1

And for

VAL1 = d and VAL2 = d2 and VAL1 = e and VAL2 = e2 => 2

And for

VAL1 = d and VAL2 = d2 and VAL1 = e and VAL2 = f => null

The Problem is, that I can not use something like:

SELECT SET
FROM MyTable
WHERE VAL1 IN (a, b, c) AND VAL2 IN (a1, b1, c1)

because it would not pay respect to particular rows and give false positives on constellations like:

SET   VAL1   VAL2
-----------------
1      c      a1
1      a      b1    
1      b      c1
2      e      d2
2      d      e2

In MySQL, IN can be used to compare row constructors :

WHERE (val1, val2) IN (
    ('a', 'a1'),
    ('b', 'b1'),
    ('c', 'c1')
)

Using group by and 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM