简体   繁体   中英

Mysql How to select all records from one table where column value is not both X and Y

I have a table with three columns:

customerID (Autoincrement INT)
ShopID (INT)
GroupID (INT)
EmailAddress (varchar)
Password (varchar)

So assuming the GroupID = 2 and I have two shopIDs (25 and 26)

I need to select all records where the customer is in GroupID 2 but in only one of the ShopIDs and insert a new record for that sme customer (with a new customerID but the rest of his other data), so that he can log in to both shops with the same email address and password.

Could anyone help me with how to select all the customerIDs that do not belong to both shops?

You can try using correlated subquery

select customerid from tablename a
where not exists 
   (select 1 from tablename b where a.customerid=b.customerid 
       and shopid in (25,26) group by customerid having count(distinct shopid)=2)

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