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

时间:2017-08-10 21:31:01

标签: 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
]

2 个答案:

答案 0 :(得分:1)

您需要按商店分组和所有非分组元素:

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 

答案 1 :(得分:1)

我认为这就是你想要的

root = logging.getLogger()
if root.handlers:
    for handler in root.handlers:
        root.removeHandler(handler)
logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)