2

我有以下实体:

class Restaurant
{
    // ...
}

class Order
{
    /**
     * The Restaurant this order belongs to.
     *
     * @var Restaurant
     */
    protected $restaurant;

    /**
     * The status of this order: 'pending', 'accepted' or 'rejected'.
     *
     * @var string
     */
    protected $status;

    // ...
}

一家餐厅可以有零个或多个订单。

我想查询所有餐厅以及订单总数,以及每个状态的订单数。

我想出了以下查询:

SELECT r, COUNT(o.id) AS totalOrders
FROM Restaurant r
LEFT JOIN Order o WITH o.restaurant = r
GROUP BY r.id

我怎样才能得到 ,pendingOrdersacceptedOrders计数rejectedOrders

4

1 回答 1

3

找到了解决方案:

SELECT r, COUNT(o.id) AS totalOrders,
  SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) AS pendingOrders,
  SUM(CASE WHEN o.status = 'accepted' THEN 1 ELSE 0 END) AS acceptedOrders,
  SUM(CASE WHEN o.status = 'rejected' THEN 1 ELSE 0 END) AS rejectedOrders
FROM Restaurant r
LEFT JOIN Order o WITH o.restaurant = r
GROUP BY r.id
于 2013-10-02T14:39:09.963 回答