订单值基于'IN'顺序 - MySQL

时间:2013-08-18 20:48:21

标签: mysql sql sorting sql-order-by

我有一个已使用其中一个属性(权重)排序的数组。然后我在查询中使用同一个数组来获取每个“对象”匹配的属性数。

SELECT objectattributelink.ID, COUNT(*) Attributes
FROM objectattributelink, attributelist
WHERE objectattributelink.ID = attributelist.AttributeID
AND attributelist.AttributeDesc IN ('Solid', 'Metal', 'Red', 'AB', 'Blue', 'Liquid', 'Plastic')
AND objectattributelink.AttributeID IN ('".implode("', '", $myArray)."')
GROUP BY objectattributelink.ID
ORDER BY Attributes DESC, Order of ID's inside 'IN' Clause DESC

我正在尝试在两个级别上对此数组进行排序:

  • 主要(最重要):根据他们匹配的属性数量(已经在查询中完成)

  • 次要:遵循ID出现在“IN”子句中的顺序(因此他们在每个“属性”组中保持其权重顺序)

第二个是我遇到问题的那个。一直在考虑使用案例,但由于数组长度不同(2-100),这不是一个选项。

注意:预订(按重量)是使用Ajax跨域调用来从其他服务器获取数据,因此无法在此查询中执行所有操作。

1 个答案:

答案 0 :(得分:0)

有两个问题。首先,您不能按列中没有出现的列进行排序。其次,你必须创建一个临时表而不是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暗示了attributeno。

另外,我不确定,但您可能还需要将订单更改为:

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