1

I have two SQL queries; First one is:

with b as (select person_id from people where name='Ward Bond' and born=1903)
select title_id from b natural join crew;

Which is producing correct results and is OK. Another one is:

with c as (select person_id from people where name='John Wayne' and born=1907)
select title_id from c natural join crew;

Which is also totally OK and producing correct results. As soon as I try to find the intersection of these two queries using the following query:

with b as (select person_id from people where name='Ward Bond' and born=1903) select title_id from b natural join crew 
intersect
with c as (select person_id from people where name='John Wayne' and born=1907) select title_id from c natural join crew;

I get the error Error: near "with": syntax error I'm using SQLite3. Can you please help me to find the problem? The thing I'm trying to get is straightforward; I want to have the intersection of these two temporary tables.

forpas
  • 160,666
  • 10
  • 38
  • 76
Reza Namvar
  • 129
  • 11

2 Answers2

2

This is the correct syntax for SQLite:

select * from (
  with b as (
    select person_id 
    from people 
    where name='Ward Bond' and born=1903
  ) 
  select title_id from b natural join crew
)
intersect
select * from (
  with c as (
    select person_id 
    from people 
    where name='John Wayne' and born=1907
  ) 
  select title_id from c natural join crew
);

Another way to get the intersected rows:

with cte(name, born) as (values ('Ward Bond', 1903), ('John Wayne', 1907))
select c.title_id 
from crew c natural join people p
where (p.name, p.born) in cte
group by c.title_id
having count(distinct p.person_id) = 2;
forpas
  • 160,666
  • 10
  • 38
  • 76
1

That's how I did it using view:

create view a as select person_id from people where name='Ward Bond' and born=1903;
create view b as select person_id from people where name='John Wayne' and born=1907;
with c as 
(select title_id from a natural join crew
intersect
select title_id from b natural join crew) 
select primary_title from c natural join titles;
Reza Namvar
  • 129
  • 11
  • 1
    You can improve the readability of your answer by formatting the SQL so that the statements are displayed across multiple lines, i.e., CREATE VIEW a AS SELECT person_id FROM people WHERE name = 'Ward Bond' AND born = 1903; – Vince I Dec 01 '21 at 14:10