我想查看哪个用户为哪个客户创建了地板设备-这两个查询都满足我的要求。但是,第二个查询的结果比第一个查询多700行。你能解释一下区别吗?
我运行了另一个查询,该查询发现了这两个集合之间的差异-确实,此查询产生了700行。因此,数据输出是相同的,但是以某种方式第二个查询捕获了更多结果。我尝试查看另外700行,但是它们看起来都很正常,并且与其他结果相似。我无法通过查看代码来发现差异,这就是我希望有人可以为我提供帮助
第一个查询
SELECT customer.name, user.name, floor_equipment.id
FROM customer, user, floor_equipment, floor, building, site
WHERE (floor_equipment.floorID = floor.ID AND floor.buildingID = building.id AND
building.siteID = site.id AND floor_equipment.created_by = user.id)
第二次查询
SELECT newTable.custName, newTable.userName, newTable.equipID
FROM (SELECT customer.name as "custName", user.name as "userName",
floor_equipment.id as "equipID", floor_equipment.created_by as "creatorID"
FROM customer, floor_equipment, floor, building, site
WHERE (floor_equipment.floorID = floor.ID AND floor.buildingID = building.id AND
building.siteID = site.id AND site.customerID = customer.ID)) as newTable, user
WHERE user.id = newTable.creatorID
我希望这两个查询都具有相同的结果,但是第二个查询比第一个查询产生700行。除了多余的行,这两个查询都导致相同的数据。另外的700行似乎是正常的,并且与其他行相似。
注意:第二个查询中有一个看似毫无意义的子查询。这样做的目的是为了优化。我正在商业智能Web应用程序Domo中运行这些查询。我写了子查询,希望它可以运行得更快。由于Domo的工作方式,前者需要2个小时,而后者则需要45秒。
答案 0 :(得分:0)
忽略(或纠正)语法错误,您的第一个查询可以编写如下:
SELECT c.name
, u.name
, fe.id
FROM customer c
CROSS
JOIN user u
JOIN floor_equipment fe
ON fe.created_by = u.id
JOIN floor f
ON f.ID = fe.floorID
JOIN building b
ON b.id = f.buildingID
JOIN site s
ON s.id = b.siteID
同样,您编写的第二条查询内容更加连贯,如下:
SELECT x.custName
, x.userName
, x.equipID
FROM
( SELECT c.name custName
, u.name userName
, fe.id equipID
, fe.created_by creatorID
FROM customer c
JOIN site s
ON s.customerID = c.ID
JOIN building b
ON b.siteID = s.id
JOIN floor f
ON f.buildingID = b.id
JOIN floor_equipment fe
ON fe.floorID = f.ID
) x
JOIN user u
ON u.id = x.creatorID
同样,我们可以省略子查询并编写它……
SELECT c.name custName
, u.name userName
, fe.id equipID
, fe.created_by creatorID
FROM customer c
JOIN site s
ON s.customerID = c.ID
JOIN building b
ON b.siteID = s.id
JOIN floor f
ON f.buildingID = b.id
JOIN floor_equipment fe
ON fe.floorID = f.ID
JOIN user u
ON u.id = fe.created_by
...因此我们可以看到第一个查询具有笛卡尔积(CROSS JOIN),而第二个查询则没有。
答案 1 :(得分:0)
您的代码是表之间的笛卡尔乘积:
customer, user, floor_equipment, floor, building, site
您的条件不是联接,而只是boiolean值的元组
floor_equipment.floorID = floor.ID,
floor.buildingID = building.id,
building.siteID = site.id,
floor_equipment.created_by = user.id
( boolean, boolean, boolean, boolean)
每个布尔值是对应匹配的结果,例如:
floor_equipment.floorID = floor.ID
因此通常返回所有行,因为对应的行不匹配
在第二个第一个笛卡尔积中,第一个结果与user.id和newTable.creatorID
的匹配行之间的连接扩展
查看您的代码可能是您需要显式的连接sintax和适当的条件