1

I am trying to create a nested SELECT SQL statment. I store all value and id and want to select rows that satisfy multiple values. How can I generate a SELECT statement using Java? For example,

ID VALUE
1  RED
2  BIG
1  SMALL
1  SMOOTH
2  TALL

.....

To select an item that is both red and small the statement would be:

SELECT * 
FROM table 
WHERE table.value = RED AND 
       id IN (SELECT * 
              FROM table 
              WHERE table.value = SMALL AND id IN (...))

3 Answers 3

1

This type of problem is called Relational Division

SELECT ID
FROM tableName
WHERE VALUE IN ('SMALL','SMOOTH')
GROUP BY ID
HAVING COUNT(*) = 2

the query above will result 1 since the ID contains both records.

If no unique constraint was enforce on value for every ID, DISTINCT is required.

SELECT ID
FROM tableName
WHERE VALUE IN ('SMALL','SMOOTH')
GROUP BY ID
HAVING COUNT(DISTINCT VALUE) = 2

OTHER(s)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This works fine if there is only one VALUE column. What if I want one more column called VALUE 2 to be added?
0
select ID
from MyTable
where VALUE in ('RED', 'SMALL')
group by ID
having count(distinct VALUE) = 2

SQL Fiddle Example

Results:

| ID |
------
|  1 |

Comments

0

Here is a general way to approach this:

select id
from t
group by id
having max(case when value = 'Red' then 1 else 0 end) = 1 and
       max(case when value = 'Small' then 1 else 0 end) = 1

In other words, membership in the set becomes a clause in the having statement. These can be both inclusion and exclusion (use = 0 instead of = 1) and optional (use or instead of and).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.