如何在 WHERE 子句(MySQL)中使用 VIEW?
Posted
技术标签:
【中文标题】如何在 WHERE 子句(MySQL)中使用 VIEW?【英文标题】:How to use VIEW in WHERE clause (MySQL)? 【发布时间】: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
如何解决?
【问题讨论】:
【参考方案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';
【讨论】:
以上是关于如何在 WHERE 子句(MySQL)中使用 VIEW?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Laravel 中 MySQL 查询的 where 子句中使用数组 [重复]
如何使用 where 子句获取 mysql 中选定行的总和?
where子句中的mysql udf json_extract - 如何提高性能