简体   繁体   中英

Select query except another table

I got 2 tables.

TABLE 1

ID  FRANCHISENAME    TELEPHONE   FRANCHISE_ID
1    BURGER          666-555-999     5
2    JSUBS           666-555-999     7
3    STEAKS          777-888-999     3

TABLE 2

ID  NAME     TELEPHONE    EMAIL           FRANCHISE_ ID
5   JOHN     555-444-333  JOHN@GMAIL.COM       5
5   JOHN     555-444-333  JOHN@GMAIL.COM       7
6   EDGARD   555-444-333  EDGARD@GMAIL.COM     9

I want to retrieve all data in table one, except for that data where the user has his email in Table 2. As for example JOHN has franchise_id 5 and 7 , so the query would only return

3 STEAKS, 777-888-999, 3

Assuming that TABLE_1 & TABLE_2 relate to each other through TABLE_1.FRANCHISE_ID & TABLE_2.FRANCHISE_ID

You can use NOT EXISTS

SELECT
*
FROM TABLE_1 T1
WHERE NOT EXISTS(
   SELECT *
   FROM TABLE_2 T2 
   WHERE T2.FRANCHISE_ID = T1.FRANCHISE_ID
   AND T2.EMAIL = 'JOHN@GMAIL.COM'
)

OR

You can use LEFT JOIN along with IS NULL

SELECT
T1.*
FROM TABLE_1 T1
LEFT JOIN TABLE_2 T2 ON T1.FRANCHISE_ID = T2.FRANCHISE_ID
WHERE T2.FRANCHISE_ID IS NULL;
SELECT t1.*
FROM
    Table1 t1
    LEFT JOIN Table2 t2
    ON t1.FRANCHISE_ID = t2.FRANCHISE_ID
    AND LEN(IFNULL(t2.EMAIL,'')) > 0
WHERE
    t2.ID IS NULL

Even if there is a record in Table 2 if it has no email it will be returned by this query. You can expand say to > 7 or more to check for a minimum level of validity of email address.

This should get you there using the NOT IN function. It will exclude records from Table 1 if there is a matching Franchise ID in Table 2, unless the email field is Table 2 is null:

SELECT * FROM Table1
WHERE Table1.Franchise_ID NOT IN
(SELECT Table2.Franchise_ID FROM Table2
WHERE Table2.Email IS NOT NULL);

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