1

i have a table as follows:

create table table1(id integer,firstname text,lastname text);

firstname lastname

======== =========
1 ben taylor
2 rob taylor
3 rob smith
4 rob zombie
5 peter smith
6 ben smith
7 peter taylor

I want to select rows with a lastname , where the lastname must be shared by ben and rob and firstnames must be ben and rob.
Hence in the above table the result of the select query must be:
1 ben taylor
2 rob taylor
3 rob smith
6 ben smith

what must be the sql query to get the above results?
I tried - select * from table1 as a,table1 as b where a.firstname='ben' and b.firstname='rob' and a.lastname=b.lastname this joined all the resultant rows which is not what i inteneded.

2 Answers 2

1

You can use two filtering joins to demand that the lastname is shared with both a Ben and a Rob:

select  *
from    Table1 t1
join    Table1 rob
on      rob.firstname = 'rob'
        and t1.lastname = rob.lastname
join    Table1 ben
on      ben.firstname = 'ben'
        and t1.lastname = ben.lastname
where   t1.firstname in ('ben', 'rob')

Live example at SQL Fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you.Suppose the database was large with its size in gigabytes,containing additional columns,wont the query containing join as you mentioned run slower than the query written by Stefan below?
The queries are basically equivalent and the database might even execute them in exactly the same way. Which actually performs better is hard to tell without testing, and performance might even depend on database or even database version.
i have edited my question to a new scenario,am sorry if am not supposed to edit the question in that way.
New scenarios belong in a new question I'd think. People should be able to read your questions and its answers without being aware of its history.
0
select * 
from table1 where first_name = 'ben' or first_name = 'rob' 
and last_name 
in (select last_name from table1 where first_name = 'rob' and last_name 
in (select last_name from table1 where first_name = 'ben'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.