【问题标题】:How to use VIEW in WHERE clause (MySQL)?如何在 WHERE 子句(MySQL)中使用 VIEW?
【发布时间】:2020-03-28 11:41:05
【问题描述】:

我想在 WHERE 子句中使用视图数据。但是出现错误:

create view post_with_answers AS
    SELECT DISTINCT postid 
    FROM (SELECT postid FROM `qa_posts` WHERE `type` = 'Q') AS q1
    INNER JOIN (SELECT parentid FROM `qa_posts` WHERE `type` = 'A') AS q2 ON q1.postid = q2.parentid

select count(*)
from qa_posts
where parentid not in post_with_answers

在最后一行我收到此错误: SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'post_with_answers' at line 3

如何解决?

【问题讨论】:

    标签: mysql sql view where-clause


    【解决方案1】:

    就像使用表格一样:

    select count(*)
    from qa_posts
    where parentid not in (select pwa.postid from post_with_answers pwa);
    

    我会提醒您不要将not in 与子查询一起使用。如果子查询中的一个值是NULL,则不会返回任何行。为此,我推荐NOT EXISTS

    select count(*)
    from qa_posts p
    where not exists (select 1
                      from post_with_answers pwa
                      where p.parentid = pwa.postid
                     );
    

    此外,您的视图定义有点过于复杂。您不需要子查询:

    create view post_with_answers AS
        SELECT DISTINCT pq.postid 
        FROM qa_posts pq JOIN
             qa_posts pa
             ON pq.postid = pa.parentid
        WHERE pq.type = 'Q' AND pa.type = 'A';
    

    那么,DISTINCT 只是增加了开销,所以EXISTS 更好:

    create view post_with_answers AS
        SELECT DISTINCT pq.postid 
        FROM qa_posts pq 
        WHERE EXISTS (SELECT 1
                      FROM qa_posts pa
                      WHERE pq.postid = pa.parentid AND
                            pa.type = 'A'
                     )
        WHERE pq.type = 'Q';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2020-04-18
      • 2019-04-16
      • 2010-09-23
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多