Mysql计数外表中的记录实例

时间:2015-02-01 00:59:16

标签: mysql sql

我在这些结构中有两个表:

Orders

-------------------------------------------------------
| id | description | created_by | price | created_at  | etc
-------------------------------------------------------

Sample data:
-------------------------------------------------------
| id | description | created_by | price | created_at  | 
-------------------------------------------------------
| 1  |   test 1    |   2        | 10.00 | 2015-10-10 00:00:00
| 2  |   test 2    |   1        | 20.00 | 2015-11-10 00:00:00
| 3  |   test 3    |   3        | 5.00  | 2015-12-10 00:00:00
| 4  |   test 4    |   10       | 100.00| 2015-01-10 00:00:00

另一张表

OrderStatus

------------------------------------
| orderid | status | comment      |
------------------------------------

------------------------------------
| orderid | status | comment      |
------------------------------------
| 1       | 1      | This is pending payment|
| 2       | 1      | This is pending payment|
| 1       | 2      |                        |
| 1       | 3      | Canceled due to shipment delay  |
| 2       | 2      | This is pending payment|
| 3       | 1      | This is pending payment|
| 4       | 1      | This is pending payment|
| 4       | 2      |                        |
| 4       | 4      | This is delivered      |

状态的可能值包括:待处理:1,PaymentMade:2,已取消:3,已交付:4等

我希望创建返回的查询/查询:

Orders stats
--------------------------------------------------------------
| total | pending |   paid     | canceled  |    delivered    |
--------------------------------------------------------------
  4        1             1            1            1

到目前为止,我已经提出了这些:

#total
SELECT COUNT(distinct a.id) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid

#pending
SELECT COUNT(distinct a.id) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid where b.status=1

#paid
SELECT COUNT(distinct a.id) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid where b.status=2

#canceled
SELECT COUNT(distinct a.id) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid where b.status=3

#delivered
SELECT COUNT(distinct a.id) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid where b.status=4

第一个查询结果(总计)与预期一致,但其余的都返回不准确的结果

任何帮助非常感谢:)

2 个答案:

答案 0 :(得分:0)

DISTINCT这不是一个好的表现实践......请尝试使用GROUP BY。

SELECT status, COUNT(1) FROM tbl_order a inner join tbl_order_status b on a.id=b.orderid GROUP BY b.status

这将导致 n 状态行,因此您可以grep每种类型的所有总和;)

答案 1 :(得分:0)

好吧,我解决了这个解决方案:

select status, count(status) from(
SELECT orderid,max(status) as status FROM tbl_order a 
inner join tbl_order_status b on a.id=b.orderid 
GROUP BY b.orderid 
order by b.orderid,b.status desc) t group by status;

此解决方案是否可以提升性能?