获取连接查询中的行数

get number of rows in join query

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

Table1: 订单table

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

Table2:项目Table

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

一个项目有多个顺序,如 table 结构所示。现在我想把订单算作每件商品。

我试过使用 join,但它给了我所有行 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`;

但我想要每件物品的数量:因为物品 1 是:2 物品 2 是:2

结论:

正如 Rahul 建议的那样:

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

所以我接受了这个答案。

您在这里缺少 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`

像这样尝试

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

您将不得不使用 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 ;