How to specify the parent query field from within a subquery in mySQL?

前端 未结 6 1016
心在旅途
心在旅途 2020-12-03 02:24

Is there a way to specify the parent query field from within a subquery in mySQL?

For Example:
I have written a basic Bulletin Board type progra

6条回答
  •  萌比男神i
    2020-12-03 03:12

    How about:

    $query = "SELECT p1.id, 
                     (SELECT COUNT(1) 
                        FROM post_table p2 
                       WHERE p2.parent_id = p1.id) as num_children
                FROM post_table p1
               WHERE p1.parent_id = 0";
    

    or if you put an alias on the p1.id, you might say:

    $query = "SELECT p1.id as p1_id, 
                     (SELECT COUNT(1) 
                        FROM post_table p2 
                       WHERE p2.parent_id = p1.id) as num_children
                FROM post_table p1
               WHERE p1.parent_id = 0";
    

提交回复
热议问题