简体   繁体   中英

MySQL Join table and count distinct users with no reference in another table

I am trying to count users that are NOT referenced in another table... Right now, I have something along the lines of this:

SELECT COUNT(DISTINCT u.id) FROM users u INNER JOIN orders o ON o.assigned!=u.id;

However, it's returning an invalid value. Any suggestions?

Thank you!

I would suggest using a LEFT JOIN between the two tables and filter the rows without a matching id in the orders table:

select count(u.id)
from users u
left join orders o
  on o.assigned = u.id
where o.assigned is null

See SQL Fiddle with Demo

Use a left join and count the rows with no match:

SELECT COUNT(*)
FROM users u
LEFT JOIN orders o
ON o.assigned = u.id
WHERE o.assigned IS NULL

An alternative is to use a NOT IN check:

SELECT COUNT(*)
FROM users
WHERE id NOT IN (SELECT distinct(assigned) FROM orders)

However, in my experience the left join performs better (assuming appropriate indexes).

SELECT COUNT(1) FROM users u 
WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.assigned=u.id);

Are you wanting a straight count (like you mentioned), or do you need values returned? This will give you the count; if you want other values, you should take one of the other approaches listed above.

假设id在users表中是唯一的,只需使用以下查询:

select count(*) From  Users as u where u.id not in (select assigned from orders)

an inner join explicitly looks for rows that match so that isn't the way to go if you are looking for non matched records

assuming that ORDERS.ASSIGNED is matched with USER.ID an outer join could return values from both and show when there aren't matches like so

select u.id, o.* from users u full outer join orders o on o.assigned = u.id;

if you only want to know which USER.ID don't have an ORDERS record you could also INTERSECT or use NOT IN () eg

select u.id from users u where id not in (select o.assigned from orders.o);

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