有两个问题。首先,您不能按未出现在 group by 中的列排序。其次,您必须创建一个临时表而不是 in。对于以后这样的事情应该可以工作:
SELECT objectattributelink.ID, COUNT(*) Attributes
FROM objectattributelink, attributelist, TABLE (VALUES ('Solid', 1), ('Metal', 2), ('Red', 3), ('AB', 4), ('Blue', 5), ('Liquid', 6), ('Plastic', 7)) AS descs(AttributeDesc, AttributeNo)
WHERE objectattributelink.ID = attributelist.AttributeID
AND attributelist.AttributeDesc = descs.AttributeDesc
AND objectattributelink.AttributeID IN ('".implode("', '", $myArray)."')
GROUP BY objectattributelink.ID
ORDER BY Attributes DESC, descs.AttributeNo
但是,这仍然无效,因为该descs.AttributeNo
列不在分组依据中。另外我不确定除了 DB2 之外的任何数据库都支持这个......
因此,要按问题修复分组,您必须将分组更改为:
GROUP BY objectattributelink.ID, descs.AttributeNo
这不应该改变分组本身,因为 ID 意味着属性号。
另外,我不确定,但您可能还必须将订单更改为:
ORDER BY 2 DESC, descs.AttributeNo
所以最终的查询看起来像这样:
SELECT objectattributelink.ID, COUNT(*) Attributes
FROM objectattributelink, attributelist, TABLE (VALUES ('Solid', 1), ('Metal', 2), ('Red', 3), ('AB', 4), ('Blue', 5), ('Liquid', 6), ('Plastic', 7)) AS descs(AttributeDesc, AttributeNo)
WHERE objectattributelink.ID = attributelist.AttributeID
AND attributelist.AttributeDesc = descs.AttributeDesc
AND objectattributelink.AttributeID IN ('".implode("', '", $myArray)."')
GROUP BY objectattributelink.ID
ORDER BY 2 DESC, descs.AttributeNo
最后,您还可以使用 row_number 不必显式输入数字:
SELECT objectattributelink.ID, COUNT(*) Attributes
FROM objectattributelink, attributelist,
(SELECT AttributeDesc, row_number() over() AS AttributeNo FROM VALUES (('Solid'), ('Metal'), ('Red'), ('AB'), ('Blue'), ('Liquid'), ('Plastic')) AS (AttributeDesc)) AS descs
WHERE objectattributelink.ID = attributelist.AttributeID
AND attributelist.AttributeDesc = descs.AttributeDesc
AND objectattributelink.AttributeID IN ('".implode("', '", $myArray)."')
GROUP BY objectattributelink.ID
ORDER BY 2 DESC, descs.AttributeNo