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:
- Create index on
parentid
field - 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
精彩评论