开发者

how optimize this mysql query?

开发者 https://www.devze.com 2023-01-30 17:13 出处:网络
i have written this mysql query: SELECT * , 1 AS haschild FROM table2 WHERE parentid = \'0\' AND pid IN ( SELECT parentid FROM table2 )

i have written this mysql query:

SELECT * , 1 AS haschild
       FROM table2
       WHERE parentid = '0'
             AND pid IN ( SELECT parentid FROM table2 )
UNION 
SELECT * , 0
       FROM table2
       WHERE parentid = '0'
             AND pid NO开发者_运维百科T IN ( SELECT parentid FROM table2 )
ORDER BY pid

but i think it is so silly query !! hope you can get my meaning of this query and guide me to write a better one.

thanks.


   SELECT t1.*,
          IF(t2.parentid IS NULL, 0, 1) AS haschild
     FROM table2 t1
LEFT JOIN table2 t2 ON t1.pid = t2.parentid
    WHERE t1.parentid = 0
 ORDER BY t1.pid

Notes:

  1. Create index on parentid field
  2. If parentid is a number - don't put quotes around


Try :

SELECT * , CASE WHEN pid IN ( SELECT parentid FROM table2 ) THEN 1 ELSE 0 END AS haschild
       FROM table2
       WHERE parentid = '0'
ORDER BY pid
0

精彩评论

暂无评论...
验证码 换一张
取 消