多个mysql查询与group by

时间:2013-11-01 23:58:31

标签: php mysql pdo

目前我正在考虑我的代码,目前我已经

$query="SELECT DISTINCT TRIPID FROM trips_info WHERE userid=$userid";
    $results = $dbh->query($query)->fetchAll();
        foreach ($results as $i => $row)
        {
            $iquery="SELECT COUNT(id) FROM trips_data WHERE userid=$userid AND tripid=$row[0]";
            $iiqu="SELECT COUNT(id) FROM trips_data WHERE userid=$userid AND not killcount=0 AND tripid=$row[0]";
            $irow=$dbh->query($iquery)->fetch();
            $iirow=$dbh->query($iiqu)->fetch();
            array_push($tripsdata, $row[0]);
            array_push($tripsdata, $irow[0]);
            array_push($tripsdata, $iirow[0]);
        }

我很清楚,必须有一种方法可以获得一个包含循环中多个数据库连接所需的所有信息的pdo。这就是我到目前为止(不起作用)

SELECT (
   (SELECT COUNT(id) as no FROM trips_data WHERE userid=1),
   (SELECT COUNT(id) as no FROM trips_data WHERE userid=1 AND not killcount=0)
) group by trips_data.tripid

我的问题是如何在这种查询中添加group by语句?

我希望得到的是

绊倒点数, 1 5322 109, 2 83939 17

3 个答案:

答案 0 :(得分:2)

如果你有什么“killcount”为null而不是0,那么它将是

SELECT tripid, count(1), count(killcount) 
FROM trips_info ti, trips_data td WHERE ti.userid=? AND td.tripid=ti.tripid
GROUP BY td.tripid

答案 1 :(得分:0)

我正在对您的数据库架构做出假设,但我认为这可以在一个查询中进行

SELECT
  ti.tripid, 
  COUNT(td_a) as 'trip_count_1', 
  COUNT(tb_b) as 'trip_count_2' 
FROM
  trips_info AS ti
INNER JOIN
  trips_data AS td_a ON td_a.tripid = ti.id
INNER JOIN
  trips_data AS td_b ON td_b.tripid = ti.id AND td_b.killcount > 0
WHERE
 ti.userid = ?

答案 2 :(得分:0)

感谢你们所有的帮助,我最后选择了不同的路线并获得了这个,这很好用

SELECT  
        tripid,
        SUM(CASE WHEN killcount >0 THEN 1 ELSE 0 END) AS kills, 
        count(id) AS points 
        FROM trips_data  
        WHERE userid=$userid
        GROUP BY tripid";