【问题标题】:Error in using WITH clause and INTERSECT in SQLite在 SQLite 中使用 WITH 子句和 INTERSECT 时出错
【发布时间】:2022-01-03 18:48:20
【问题描述】:

我有两个 SQL 查询; 第一个是:

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

这会产生正确的结果并且可以。 另一个是:

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

这也完全可以并产生正确的结果。一旦我尝试使用以下查询找到这两个查询的交集:

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;

我收到错误Error: near "with": syntax error 我正在使用 SQLite3。你能帮我找出问题吗?我想要得到的东西很简单;我想要这两个临时表的交集。

【问题讨论】:

    标签: sqlite select with-statement intersect


    【解决方案1】:

    这是 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
    );
    

    另一种获取相交行的方法:

    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;
    

    【讨论】:

    • 感谢您的指导。使用“视图”也可以
    【解决方案2】:

    我就是这样使用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;
    

    【讨论】:

    • 您可以通过格式化 SQL 来提高答案的可读性,以便语句跨多行显示,即 CREATE VIEW a AS SELECT person_id FROM people WHERE name = 'Ward Bond' AND Born = 1903;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    相关资源
    最近更新 更多