我有 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/