简体   繁体   中英

SQL Query for finding what results are not in a table

I am a little bit rusty on my SQL and would like some help with these queries that I am struggling getting my head round or even finding out if it is possible.

Hi so I have some tables;

clients,products,clientproducts

when a client opts in for a product that is added to clientproducts, using the clientid and the productid.

the easy query I want to run a query that will only show me products the client has opted in for.

the harder one I also want to run a query that will show me just the clients that haven't opted in for a product/s.

Thank you for your help in advance.

Query 1:

   SELECT table1.id1 FROM table1
    WHERE table1.id1 IN (SELECT table2.foreign_id FROM table2);

Query 2:

      SELECT table1.id1 FROM table1
        WHERE table1.id1 NOT IN (SELECT table2.foreign_id FROM table2);

here, use LEFT JOIN

SELECT  a.*
FROM    products a
        LEFT JOIN clientproducts b
            ON a.productID = b.productID
        LEFT JOIN clients c
            ON  b.clientID = c.clientID AND
                c.ClientID = 'clientID HERE'
WHERE   c.client IS NULL

OR

SELECT  a.*
FROM    products a
        LEFT JOIN clientproducts b
            ON a.productID = b.productID AND
               b.ClientID = 'clientID HERE'
WHERE   b.productID IS NULL

The easy query

SELECT * FROM clients LEFT JOIN products ON clients.id = products.client_id

The hard query

SELECT * FROM clients WHERE clients.id NOT IN (SELECT clients.id FROM clients LEFT JOIN products ON clients.id = products.client_id)

Get all the products information where client_id = 1

select products.*
from products, clientproducts
where products.id = clientproducts.product_id
and clientproducts.client_id = 1

Get all the clients details who has not opted for any products

select *
from clients
where id not in (select client_id
            from clientproducts)

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