1

I am finding it hard to build a SQL, on the following database schema,

Shop

id
name

Order

id
shop_id
date
amount

You can see that a shop can have many orders. I would like to a build a SQL that gives the number of orders of each shop on a specific date. So the WHERE part must be (e.g. 2011-7-13),

WHERE order.date = '2011-7-13'

I can't think of how the SELECT part should be like. I think COUNT(*) should be used but this is all what I have got in my brain now.

Could somebody please give some hints on this?

Many thanks to you all.

4

4 回答 4

2

Try this:

SELECT a.id, a.name, COUNT(1) AS order_count
  FROM Shop a INNER JOIN Order b
    ON a.id = b.shop_id
 WHERE `date` = '2011-7-13'
 GROUP BY a.id, a.name
于 2011-07-12T20:09:19.817 回答
1

try this:

SELECT COUNT(Order.id), Shop.name, Order.date
FROM Shop INNER JOIN Order ON Shop.id=Order.shop_id
WHERE Order.date = '$date'
GROUP BY Shop.name, Order.date
ORDER BY Order.date

I've included date in the results for verification.

于 2011-07-12T20:08:47.600 回答
1
SELECT Shop.name, COUNT(*) AS Num_Orders
FROM Shop JOIN `Order` ON Shop.id = `Order`.id
WHERE DATE(`Order`.`date`) = '2011-7-13'
GROUP BY `Order`.id;

Note, in case date is a DATETIME column I used the DATE() function to return only the date part of it, not the time.

You'll probably have to quote date and Order in backquotes as above, since they're reserved MySQL keywords. Maybe not date but almost certainly Order.

于 2011-07-12T20:09:24.673 回答
1

After some consideration (and @AJ's well deserved remark), here's my (revised) answer.

SELECT shop.id, shop.name,
FROM shop
JOIN (SELECT shop_id, date, COUNT(*)
      FROM order
      WHERE date = :date
      GROUP BY shop_id, date) as order_count
ON order_count.shop_id = shop.id

If you want a list of all order counts by date, remove the inner WHERE clause.

于 2011-07-12T20:34:53.033 回答