从SQL表中计算第2组的列

时间:2013-11-24 19:14:05

标签: php mysql sql codeigniter

我正在使用这样的表结构:

departure | destination | Type    | Pilot
EDDK        EDDM          flight    name
EDDK        EDDI          flight    name
EDDI        EDDK          flight    name
EDDK        EDDP          flight    name
EDDM        EDDK          flight    name
EDDF        EDDK          flight    name
EDDF        EDDI          flight    name

and so on...

现在我正在使用这样的codeigniter sql查询:

$query = $this->db->select('departure, COUNT(departure) as zaehler', False)
                    ->from('tablename')
                    ->where('Pilot', $user)
                    ->where('Type', 'flight')
                    ->group_by('departure')
                    ->order_by('zaehler', 'DESC')
                    ->get();

return $query->result();

这会产生一个预期的数组:

Array
(
   [0] => stdClass Object
      (
        [departure] => EDDK
        [zaehler] => 3
     )

   [1] => stdClass Object
      (
        [departure] => EDDF
        [zaehler] => 2
      )

   [2] => stdClass Object
      (
        [departure] => EDDM
        [zaehler] => 1
      )
   [3] => stdClass Object
      (
        [departure] => EDDI
        [zaehler] => 1
      )

我也对“目的地”使用相同的查询。 是否有可能只获得这两个查询的结果? 结果看起来像这样吗?

Array
  (
   [0] => EDDK
      (
        [departure] => 3
        [destination] => 3
     )

   [1] => EDDF
      (
        [departure] => 2
        [destination] => 0
      )

   [2] => EDDM
      (
        [departure] => 1
        [destination] => 1
      )
   [3] => EDDI
      (
        [departure] => 1
        [destination] => 2
      )
   [4] => EDDP
      (
        [departure] => 0
        [destination] => 1
      )

2 个答案:

答案 0 :(得分:0)

我会留给你把它翻译成你的php格式,但查询的一般形式是这样的:

SELECT Departure, DepCnt, DesCnt FROM
(SELECT Departure, COUNT(Departure) AS DepCnt FROM T
GROUP BY Departure)
INNER JOIN
(SELECT Destination, COUNT(Destination) AS DesCnt FROM T
GROUP BY Destination)
ON Departure = Destination

如评论中所述,上述解决方案将在没有离开或没有目的地时省​​略位置。以下修改涉及此问题。

SELECT Loc, COALESCE(DepCnt,0), COALESCE(DesCnt,0) FROM
(SELECT DISTINCT Departure AS Loc FROM T
UNION
SELECT DISTINCT Destination FROM T)
LEFT OUTER JOIN
(SELECT Departure, COUNT(Departure) AS DepCnt FROM T
GROUP BY Departure) ON Departure = Loc
LEFT OUTER JOIN
(SELECT Destination, COUNT(Destination) AS DesCnt FROM T
GROUP BY Destination) ON Destination = Loc

答案 1 :(得分:0)

$sqlQuery = "SELECT distinct departure,";
$sqlQuery .= "  (SELECT count(*) FROM tablename b WHERE b.departure = a.departure) as 'departure',";
$sqlQuery .= "  (SELECT count(*) FROM tablename b WHERE b.destination = a.destination) as 'destination'";
$sqlQuery .= "FROM tablename a ";

$query = $this->db->query($sqlQuery);

return $query->result();

这将计算每个“目的地”的所有出发地和目的地。您可以随意添加“WHERE”语法或以您自己的方式进行改进