mysql - 从 MySQL 查询中的 3 个表中获取数据

标签 mysql sql

我有 3 个结构如下的表:

store_locations
id        store_id        zip_code        city        state        last_updated
--------------------------------------------------------------------------------
1         7438            37493           Seattle     WA           [timestamp]
1         7587            89574           Spokane     WA           [timestamp]


store_vehicles
id        store_id        vin_number
--------------------------------------------------------------------------------
1         7438            [some vin number]
1         7587            [some vin number]


store_sold_vehicles
id        vin_number
--------------------------------------------------------------------------------
1         [some vin number]
1         [some vin number]

我正在尝试输出一个包含商店详细信息的表格,其中包括该位置的 total_sales。这是我正在尝试的查询,但它不起作用,因为我缺少 GROUP BY 语句但不知道如何添加它。

   SELECT
      COUNT(sales.id) AS total_sales,
      locations.store_id AS store_id,
      locations.zip_code AS zip_code,
      locations.city AS city,
      locations.state AS state
    FROM store_locations locations
      INNER JOIN store_vehicles vehicles ON vehicles.store_id = locations.store_id
      INNER JOIN store_sold_vehicles sales ON sales.Vin = vehicles.Vin
    GROUP BY vehicles.Vin

这是否可以在没有多个查询的情况下实现?

编辑:预期的输出是这样的:

[
  'store_id'=>8239,
  'zip_code'=>27103,
  'city'=>'San Francisco',
  'state'=>'CA',
  'last_updated'=>[timestamp],
  'total_sales'=>121
]

最佳答案

您需要按商店和所有未分组的元素进行分组:

SELECT
  COUNT(sales.id) AS total_sales,
  locations.store_id AS store_id,
  locations.zip_code AS zip_code,
  locations.city AS city,
  locations.state AS state
FROM store_locations locations
  INNER JOIN store_vehicles vehicles ON vehicles.store_id = locations.store_id
  INNER JOIN store_sold_vehicles sales ON sales.Vin = vehicles.Vin
GROUP BY locations.store_id, locations.zip_code, locations.city, locations.state 

关于mysql - 从 MySQL 查询中的 3 个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45623742/

相关文章:

php - 排序具有不同位数的MySQL数据

javascript - Sails.js 上传后如何获取图像的名称

sql - 在每个新的连续簇上重置为 0 的运行总和

sql - 影响连接的 where 子句

php - $$(双美元)在 mysql 上下文中有何用途?

java - 应用程序连接到数据库

PHP、MySQL、PDO 事务 - 调用 commit() 后是否可以使用 rollBack()?

sql - HH 中的每小时平均聚合 = (HH-1) :41 - HH:40 format in PostgreSQL

mysql - 如何删除超过一定数量的表的所有记录以进行清理

python - 复杂 SQL 优化与通用语言