获取连接查询

时间:2017-07-31 12:35:40

标签: php mysql rowcount

我在不同的表格中保存物品和订单。我想按项目计算订单。 这是我的表结构。

表1:订单表

id | table2_id
1  | 1 
2  | 1 
3  | 2 
4  | 2

表2:项目表

id | user_id
1  | 1 
2  | 2 
3  | 1
4  | 2 

一个项目有多个订单,如表格结构所示。现在我想把订单计算为每个项目。

我尝试过使用连接,但它给了我所有行cont:4

SELECT count(Table1.id) as order_count_for_each_item
FROM `Table2` as `t2`
LEFT OUTER JOIN `Table1` as `t2` ON `t1`.`id` = `t2`.`table2_id`;

但是我希望每个项目都计数:因为For Item1是:2而Item2是:2

结论:

正如拉胡尔建议的那样:

SELECT count(*) as order_count_for_each_item
FROM `Table2` as t2
LEFT OUTER JOIN `Table1` as t1 ON `t1`.`table2_id` = `t2`.id
GROUP BY t1.`table2_id`

这个查询给我最初想要的结果。

order_count_for_each_item
1  |
2  |

但是我接受的答案(Bibhudatta Sahoo)给了我项目计数零,以及项目标准顺序的计数。

SELECT t2.`id`,
(SELECT count(t1.id) form `Table1` as t1 
 where t2.`id` = t1.`table2_id`) as order_count_for_each_item
FROM `Table2` as t2
group by t2.`id`
order by t2.`id` asc

Item ID |  order_count_for_each_item
1       |   2
2       |   2
3       |   0
4       |   0

所以我接受了这个答案。

3 个答案:

答案 0 :(得分:1)

您在这里缺少group by

SELECT count(*) as order_count_for_each_item
FROM `Table2` as t2
LEFT OUTER JOIN `Table1` as t1 ON `t1`.`table2_id` = `t2`.id
GROUP BY t1.`table2_id`

答案 1 :(得分:1)

尝试这样

SELECT t2.`id`,
(SELECT count(t1.id) form `Table1` as t1 
 where t2.`id` = t1.`table2_id`) as order_count_for_each_item
FROM `Table2` as t2
group by t2.`id`
order by t2.`id` asc

答案 2 :(得分:0)

您必须使用aggregate函数Group bygroup您对项目的数据并获取计数。

SELECT item.id,ifnull(count(order.id),0) as order_count_for_each_item
FROM `Table2` as `item`
LEFT JOIN `Table1` as `order` ON order.table2_id=item.id
group by item.id ;