How to use VIEW in WHERE clause (MySQL)?

Midriaz :

I want to use data of view in WHERE clause. But getting an error:

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

On the last row I am getting this error: 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

How to fix that?

Gordon Linoff :

Just like you would use a table:

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

I would caution you from using not in with a subquery. No rows are returned if even one value from the subquery is NULL. For this reason, I recommend NOT EXISTS:

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

In addition, your view definition is a bit over complicated. You don't need subqueries:

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';

Then, the DISTINCT just adds overhead, so EXISTS is better:

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';

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371689&siteId=1