MYSQL Check if every item that exists within one table, exists in another

APorter1031 :

How can I check if all the items in one table exists within another. For example, consider the following two tables.

With their respective query:

SELECT orderID
FROM orders
WHERE customer_id = 1;

TABLE A
-------

orderID
2
1
6
4
SELECT orderID
FROM orders
WHERE customer_id = 2;

TABLE B
-------

orderID
5
1
7
9

I would not want to output anything because all the items from TABLE A do not exist within TABLE B.

However, I were to have:

SELECT orderID
FROM orders
WHERE customer_id = 3;

TABLE C
-------

orderID
5

I would want to output it because all the items within TABLE C are in TABLE B.

If I were to do a select with TABLE C, I would expect table C to be the output.

I have tried the following query:

SELECT *
FROM (SELECT orderID
FROM orders
WHERE customer_id = 1) A
WHERE A.orderID IN (
SELECT orderID
FROM orders
WHERE customer_id = 2);
Andrew :

If you can to check in a by-customer basis, you can do this:

IF (NOT EXISTS
    SELECT NULL
    FROM orders
    WHERE customer_id = 1 -- "Table A"
    AND orderID NOT IN 
        -- "Table B"
        (SELECT orderID
        FROM orders
        WHERE customer_id = 2)
    )
    SELECT orderID
    FROM orders
    WHERE customer_id = 1;

Here the query basically gets the orders from table A which are not in table B. If there is none, it then performs the select at the end. Otherwise, it does nothing.

If you use customer_id = 3 instead, you get one row with orderID 5 ("table C").

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23779&siteId=1