0

目前我正在重构我的代码,目前我有

$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

4

3 回答 3

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
于 2013-11-02T00:13:39.057 回答
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 = ?
于 2013-11-02T00:15:07.193 回答
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";
于 2013-11-02T01:08:16.423 回答