Midriaz:
私は、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
それをどのように修正するには?
ゴードン・リノフ:
ちょうどあなたがテーブルを使用するように:
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';