如何从mySql中的anther获取一个表中的项目列表及其相关项目的总数?

时间:2017-12-23 12:05:22

标签: mysql sqlfiddle

我将列出所有order_status项目,其中包含相关订单总数。我尝试使用内连接和左连接,但它们都不适合我。

select
order_status.order_status_id, order_status.name, sum(order.order_id)
where language_id = 1

http://sqlfiddle.com/#!9/7efcbe

以下是表格:

CREATE TABLE IF NOT EXISTS `order` (
    `order_id` int(11) NOT NULL AUTO_INCREMENT,
    `store_id` int(11) NOT NULL DEFAULT '0',
    `order_status_id` int(11) NOT NULL DEFAULT '0',
    `language_id` int(11) NOT NULL,
    PRIMARY KEY (`order_id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `order_status` (
    `order_status_id` int(11) NOT NULL AUTO_INCREMENT,
    `language_id` int(11) NOT NULL,
    `name` varchar(32) NOT NULL,
    PRIMARY KEY (`order_status_id`,`language_id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3 个答案:

答案 0 :(得分:2)

以下是查询,也许您正在寻找此数据 -

select os.order_status_id,os.name,count(o.order_id) 
from order_status as os 
left outer join `order` o on os.order_status_id = o.order_status_id
group by os.order_status_id,os.name

答案 1 :(得分:0)

尝试:

select os.order_status_id, os.name, sum(o.order_id)
from `order_status` os JOIN `order` o on os.order_status_id=o.order_status_id
AND o.language_id = 1
GROUP BY o.order_status_id;

答案 2 :(得分:0)

您可以针对您的问题尝试此解决方案:

select order_status.order_status_id,order_status.name,count(o.order_id) AS no_of_order
from order_status 
left outer join `order` o on order_status.order_status_id = o.order_status_id
group by order_status.order_status_id,order_status.name

您还可以访问http://sqlfiddle.com/#!9/7efcbe/22