如何优化这个mysql查询?

时间:2010-12-14 11:38:47

标签: mysql

我写了这个mysql查询:

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 NOT IN ( SELECT parentid FROM table2 )
ORDER BY pid

但我认为这是如此愚蠢的查询!! 希望你能理解我对这个问题的看法,并指导我写一个更好的查询。

感谢。

2 个答案:

答案 0 :(得分:2)

   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

注意:

  1. parentid字段
  2. 上创建索引
  3. 如果parentid是一个数字 - 请不要在
  4. 周围加上引号

答案 1 :(得分:0)

尝试:

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