mysql - 如何借助 group by 子句在一个查询中获取两个不同表的不同行数

标签 mysql database oracle11g database-administration

我有一个父表(订单)和一个子表(项目)。一个用户一天可以下多个订单,一个订单可能有多个商品。

我的表结构如下,

Order Table Item table

我想得到这样的结果,即特定用户订购了多少订单和商品。

我需要这样的结果

Result

谢谢。

最佳答案

尝试对计数列使用不同计数,并且按 user_id 分组就足够了:

select o.user_id as "User Id",
       count(distinct o.id_order) as "Count(Order)",
       count(distinct i.id_item) as "Count(Item)",
       max("date") as "Date"
  from orders o
  join item i on o.id_order = i.id_order
 group by user_id;

User Id Count(Order)  Count(Item)    Date
------- ------------  -----------  ----------
   1         3            7        22.11.2018

Rextester Demo

关于mysql - 如何借助 group by 子句在一个查询中获取两个不同表的不同行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432193/

相关文章:

php - 图片上传不起作用,我也没有收到错误消息

docker - 将数据持久保存在 Oracle 数据库的 docker 卷中

MySQL 连接查询两个表中的最大日期

MySQL 子查询使用 GROUP BY 对多个列进行计数

非关系型数据库系统

database - 删除表中的所有记录

linux - 在 Linux 6 中运行 ./runInsaller for Oracle 11g 安装无法使用命令执行自动检查显示颜色

java - 从 Oracle 中的远程表插入本地表

php - 在 MySQL 查询中的 where 子句中传递变量 PHP CodeIgniter

database - 在 Couchbase 中交换存储桶