Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query similar to IN where clause with AND condition instead of OR

I am trying to optimize my SQL query, so that we will not have to process the response on our JVM.

Consider we have following table with entries:

+-----------+-------------+
| Column1   | Column2     |
+-----------+-------------+
|val11      |val21        |
|val11      |val22        |
|val11      |val23        |
|val12      |val21        |
|val12      |val24        |
+-----------+-------------+

Now, I want execute a query which will result me column1s having rows mapped to Column2s values val21, val22, val23.

Something similar to IN where clause, but, as IN where clause searches for data with OR between the values of IN clause, I want to search for AND in between these values.

For IN where clause:

SELECT Column1 from table
WHERE Column2 IN (val21, val22, val23)

will result in both val11 and val12 (as IN clause will check for data with val21, or val22 or val23).

Instead I want to have some query which will check Column1 having mapping with all three val21, val22, val23 as we have for val11.

Using Informix DB.

like image 855
Krishna Kumar Avatar asked Jun 30 '17 09:06

Krishna Kumar


People also ask

Which operator is similar to the WHERE clause in SQL?

SQL Server LIKE operator overview The LIKE operator is used in the WHERE clause of the SELECT , UPDATE , and DELETE statements to filter rows based on pattern matching.

What can be used instead of OR in SQL?

Often rewriting OR as UNION helps. You could tidy this up somewhat by encapsulating the join of c and b into a CTE and referencing that in both branches of the UNION instead of repeating it - or materialising into a temp table if that initial join is itself expensive.

How do you do multiple conditions in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.

Can we use HAVING AND WHERE clause in same query?

A query can contain both a WHERE clause and a HAVING clause. In that case: The WHERE clause is applied first to the individual rows in the tables or table-valued objects in the Diagram pane. Only the rows that meet the conditions in the WHERE clause are grouped.


1 Answers

This is called "relational division".

The usual approach for this, is something like the following:

select column1
from x
where column2 in ('val21', 'val22', 'val23')
group by column1
having count(distinct column2) = 3;

Note that this would also include values that have more then those three values assigned in column2 (so it returns those that have at least those three values)

like image 70
a_horse_with_no_name Avatar answered Nov 14 '22 21:11

a_horse_with_no_name