0

我有两张桌子。barcodesbarcodes_entered

barcodes

id | product    | barcode
-------------------------
1  | product1   | 12345
2  | product2   | 23456
3  | product3   | 34567

barcodes_entered

barcode_id | timestamp 
--------------------------------
2          | 2013-07-01 00:00:00
2          | 2013-07-01 00:00:00
3          | 2013-07-01 00:00:00
2          | 2013-07-02 00:00:00
1          | 2013-07-02 00:00:00

我试图弄清楚每种产品每天输入多少条码。

所以我从上面的预期结果是:

product  | count  | date
------------------------------
product1 | 0      | 2013-07-01
product2 | 2      | 2013-07-01
product3 | 1      | 2013-07-01
product1 | 1      | 2013-07-02
product2 | 1      | 2013-07-02
product3 | 0      | 2013-07-02

我现在尝试编写的查询如下所示:

SELECT product, COUNT( barcode_id ) AS count, DATE(  `timestamp` ) AS date
FROM barcodes_entered
LEFT JOIN barcodes ON barcodes.id = barcodes_entered.barcode_id
GROUP BY DATE(  `timestamp` ) ASC

不幸的是,这给出了以下结果:

product  | count  | date
------------------------------
product1 | 3      | 2013-07-01
product2 | 2      | 2013-07-02

所以从技术上讲,我我要问的是,我如何按日期分组,然后再按产品分组,同时计算所述产品输入了多少条码?

4

2 回答 2

2

date与和分组product

GROUP BY DATE(  `timestamp` ) ASC, product

更新

为了获得zero结果,我认为您应该使用JOIN而不是LEFT JOIN

于 2013-07-03T07:57:19.357 回答
1

而是从条形码中选择,然后加入barcodes_entered。未经测试,但应该可以工作。

SELECT product, COUNT( barcode_id ) AS count, DATE(  `timestamp` ) AS date
FROM barcodes
LEFT JOIN barcodes_entered ON barcodes.id = barcodes_entered.barcode_id
GROUP BY DATE(  `timestamp` ) ASC, product
于 2013-07-03T08:05:01.787 回答