三个相关表的SQL查询

时间:2015-08-17 17:47:40

标签: mysql database

我无法整理MySQL查询。

我有一个包含三个表的数据库:Location,LocationTypes和LocationStatus。

我需要检索每个位置的每种状态的总和。所以,我的结果应该是这样的:

id_LocationType, status, total
1, open, 200
1, closed, 100
2, open, 400
2, closed, 500

查询应该访问三个表。

LocationTypes - <地点 - < LocationStatus

我想出了这个:

SELECT status, COUNT(DISTINCT id_Locations)
    FROM LocationStatus
    GROUP BY status

但这并没有通过LocationType给我状态,它给出了每种状态的总状态,结合了所有LocationTypes:

status, value
open, 600
closed, 600

它没有区分LocationType(来自LocationType表)。此外,它还会计算所有状态值。但是,由于位置可以有多个状态记录(即每次更新状态时都会创建记录),我只想将最新状态更新计为有效状态。

架构如下所示:

Locations Table
-- id (PK)
-- id_LocationType (FK to LocationTypes Table)
-- name 
-- date_created
-- date_modified

LocationTypes Table
-- id (PK)
-- nameLocationType 
-- date_created
-- date_modified

LocationStatus Table
-- id (PK)
-- id_Location (FK to Location Table)
-- status
-- date_created
-- date_modified 

所以,它是这样链接的:

LocationTypes - <地点 - < LocationStatus

如何整理此查询?

2 个答案:

答案 0 :(得分:2)

您需要按LocationTypestatus对结果进行分组。试试这个:

SELECT id_LocationType, status, COUNT(DISTINCT id_Locations)
FROM Locations join LocationStatus
     ON Locations.id = LocationStatus.id_Location 
GROUP BY id_LocationType, status

答案 1 :(得分:0)

我希望此查询对您有所帮助。

select lt.id as id_LocationType , ls.status,count(*)
    from LocationTypes as lt join Locations as l join LocationStatus as ls
    on lt.id=l.id_LocationType and on l.id=ls.id_location 
    Group by lt.id,ls.status.