1

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 NOT 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.

2 Answers 2

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

Notes:

  1. Create index on parentid field
  2. If parentid is a number - don't put quotes around
Sign up to request clarification or add additional context in comments.

2 Comments

why do not put quotes around number fields?
@hd: because in some cases in some reason mysql tries to cast the field to the char too (not the char to numeric) and you lose the chance to get the query be optimized by index.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.