简体   繁体   中英

How can I select items from one sql table that don't appear in another table

I have a Customer table which has an ID. Each Customer entry has a Design which is stored in a Design table (it contains the CustomerID to reference).

In my scenario, a Customer can have several Designs and sometimes no Designs. How could I select Customers that only have Designs?

I've tried doing an Inner Join like this but I still get too many records since a Customer can have many Designs:

Select * from Customer
Inner Join Design
On Design.CustomerID = Customer.ID
Where Design.CustomerID is not null

* select all records of all tables. Use tablename.* to select only all records of a specific table.

Select Customer.*
from Customer
Inner Join Design
On Design.CustomerID = Customer.ID

But actually you are always better off by explicitly defining which columns you need. So use

Select Customer.ID, Customer.Col2, Customer.Col3
from Customer
Inner Join Design On Design.CustomerID = Customer.ID
group by Select Customer.ID, Customer.Col2, Customer.Col3

And when you use an inner join then only the records will be returned that actually have a link to the joined table - so your where clause is obsolete.

i guess you storing an empty strings in your database .

try that

  Select * from Customer
  Inner Join Design
  On Design.CustomerID = Customer.ID
  Where Design.CustomerID is not null
  AND Design.CustomerID != ''
  GROUP BY Customer.ID

You can do a where exists

select * from Customer
where exists (select 1 from Design where CustomerId = Customer.ID)

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