简体   繁体   中英

Not able to merge results from the three select statements

Hey look here i am trying to get result from these three select statements at once but i am noit able to do so. So please help me in rectifying my mistake. Don't rate me negative if you found my english or question method bad.

 $sql = $conn->prepare("SELECT Count(c.c_id) from complaints c, users u,cell_num cn where c.status=? AND c.u_id_fk=u.u_id AND u.u_id=cn.u_id_fk");
 $sql->bind_param("i",$statOpen);

 $sql .= $conn->prepare("SELECT Count(c.c_id) from complaints c, users u,cell_num cn where c.status=? AND c.u_id_fk=u.u_id AND u.u_id=cn.u_id_fk");
 sql->bind_param("i",$statProgress);

 $sql .= $conn->prepare("SELECT Count(c.c_id) from complaints c, users u,cell_num cn where c.status=? AND c.u_id_fk=u.u_id AND u.u_id=cn.u_id_fk");
 $sql->bind_param("i",$statClosed);

                        $sql->execute();

                        $sql->store_result();

                        if($sql->num_rows > 0)
                        {
                            $sql->bind_result($c_id);

                            while( $sql->fetch() )
                            {
                                $user[] = array(
                               'c_id'=>$c_id


                             );
                            }
                            echo json_encode($user);


                            $sql->close();
                        }

You can do conditional aggregation:

select 
    sum(c.status = ?) cnt_open,
    sum(c.status = ?) cnt_progress,
    sum(c.status = ?) cnt_closed
from complaints c
inner join users u on u.u_id = c.u_id_fk
inner join cell_num cn on cn.u_id_fk = u.u_id

This query accepts three parameters at once, that correspond to the three values that you were passing to your three individual queries.

Note that I modified the query to use standard joins (with the on keyword) rather than old-school, implicit joins (with commas in the from clause): this archaic syntax should not be used in new code.

You can make the query more efficient by adding a where clause that filters on the three possible status es (this requires passing each parameter twice):

where c.status in (?, ?, ?)

you can do so, it's more optimised

select c.statut,count(c.c_id)
from complaints c
inner join users u on u.u_id = c.u_id_fk
inner join cell_num cn on cn.u_id_fk = u.u_id
where c.status in (?, ?, ?)
group by c.status

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM