skip to Main Content

I have two queries that I want to run against a certain type of product, to check whether a product exists with certain specifications.

Therefore I first want to check if a product contains a type=A, and if so check again if it either contains type=B or C.
How can I combine this both into a single query?

table cars:

id;product;type
0;car;A
1;car;B
2;car;C

Current two-step SQL:

SELECT 1 FROM cars where product = 'car' and type = 'A';

if so:

SELECT 1 FROM cars where product = 'car' AND (type = 'B' OR type = 'C');

2

Answers


  1. It sounds like you need to combine them with exists, such as

    select *
    from t
    where product = 'car' and type = 'A'
    and exists (
      select * from t t2
      where t2.product = t.product and t2.type in ('B', 'C')
    );
    
    Login or Signup to reply.
  2. Assuming product is "grouping" field in your table you might need something like this.

    SELCET * FROM cars c
    WHERE EXISTS(SELECT 1 FROM cars where product = c.product and type = 'A')
    AND EXISTS(SELECT 1 FROM cars where product = c.product AND type IN ('B', 'C'))
    AND c.product = 'car'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search