我在我的数据库中执行这两个查询。第一个返回1个记录,第二个返回2241(正如我预期的那样)。我问同样的事情,但是以两种不同的方式。在第一个中,我使用DISTINCT
,在第二个中我使用" GROUP BY"。 Aren这些是一样的吗?
/*returns 1 record*/
SELECT DISTINCT INVENTORY.location, INVENTORY.label, INVENTORY.version, SUM(INVENTORY.quantity) AS total, LABELS.description, LABELS.customer , LABELS.label
FROM INVENTORY
INNER JOIN LABELS
ON INVENTORY.label = LABELS.label
AND INVENTORY.version = LABELS.version
WHERE INVENTORY.location = 1
/*returns 2241 record*/
SELECT Inventory.location, Inventory.label, Inventory.version, SUM(INVENTORY.quantity) AS total, Labels.description, Labels.customer, LABELS.label
FROM Inventory
INNER JOIN LABELS
ON Inventory.label = Labels.label
AND Inventory.version = Labels.version
WHERE Inventory.location = 1
GROUP BY Inventory.label, Inventory.Version
答案 0 :(得分:1)
根据ANSI SQL,您的查询都是无效的,但这并没有阻止Oracle发布MySQL,也没有阻止您编写这些查询。以下是您尝试的两个查询的有效版本:
SELECT Inventory.location,
Inventory.label,
Inventory.version,
SUM(INVENTORY.quantity) AS total,
Labels.description,
Labels.customer,
LABELS.label
FROM Inventory
INNER JOIN LABELS
ON Inventory.label = Labels.label AND
Inventory.version = Labels.version
WHERE Inventory.location = 1
GROUP BY Inventory.location,
Inventory.label,
Inventory.version,
Labels.description,
Labels.customer,
LABELS.label
这里的关键点是SELECT
子句中出现的每一列也出现在GROUP BY
子句中或出现在聚合函数中,例如{{1 }}
您的查询在SQLite上运行,因为它与MySQL兼容,而对查询的严格要求不严格。