简体   繁体   中英

Easiest way to self-join one table to create “AND-filter”?

I have the following (very simple) table:

| A | Z |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 5 |

Now I want to filter the values in this table by Z and find all As that match my filter. The Z-Filter should behave like an AND-filter. Here are some examples with matching queries:

-- filter z= 1
-- expect a = 1,2
select a from data where z = 1;

-- filter z= 5
-- expect a = 2
select a from data where z = 5;

-- filter z= -
-- expect a = 1,2
select a from data;

Now here comes the problem: I want to filter by z=1 AND z=5

-- filter z: 1,5
-- expect a = 2

Using "in" will not give the result I want. It's like saying z=1 OR z=5.

select a from data where z in (1,5);

I want an AND-join to the z-filter. I know it can be done like this:

select d1.a from data d1
  left join data d2 on (d1.a = d2.a)
  where d1.z = 1
  and d2.z = 5;

The thing is that the z-filter-list can grow dynamically and for every z-value I have to add another join. So my question is: Is there an easier way to do this?

SQLFiddle with the above examples: http://sqlfiddle.com/#!2/03d07/4

You can use GROUP BY/HAVING :

SELECT  a
FROM    data 
WHERE   z IN (1,5)
GROUP BY a
HAVING COUNT(DISTINCT z) = 2; -- NUMBER OF ITEMS IN THE IN CLAUSE

So although you are saying z can be 1 or 5, your HAVING limits this to only values of a that have both.

Example on SQL Fiddle

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