The below SQL query gets all the ids which have different last names.
No it doesn't.
Why the query in the question doesn't return all the names which have
different last names?
Because it doesn't take in consideration same names.
In simple words in the example below, which are the names that have different last names ?
Answer. John and Anna.
You are selecting the rows with first_name in (John,Anna)
, but with this condition the rows John Smith
and Anna Smith
are returned.
Follow below example:
CREATE TABLE names (
`first_name` VARCHAR(15),
`last_name` VARCHAR(15) );
INSERT INTO names VALUES
('John','Smith'),
('John','Test2'),
('Anna','Maria'),
('Anna','Smith'),
('Ron','Smith'),
('Maria','Smith');
Based on the SQL query gets all the ids which have different last names.
the query in the question must return only below values,
first_name last_name
John Test2
Anna Maria
but it doesn't, it gives:
first_name last_name
John Smith
John Test2
Anna Maria
Anna Smith
Why is wrong result returned ?
When you need to select names which have different last names you have to use a condition where last_names count is equal to 1.
Maybe you are trying to use:
select *
from names
where last_name in ( select last_name
from names
group by last_name
having count(*) = 1
)
which will return only the names that doesn't share last_names
Check the fiddle.