我正在努力寻找一种通过 SELECT 查询合并数据的方法。表格如下:
sku condition make model derivative height length depth
-------------------------------------------------------------------------------------------
123 new ford test 212 1.28 9.0
234 new ford test 212
345 new ford test 212 4.9
456 new bmw awesome 3.33 3.33
789 new bmw cool 123 2.23 9.89
987 new bmw cool 123 1.99
... ... ... ... ... ... ...
我需要做的就是按“最佳可用”数据进行分组。我尝试按每一列进行分组,但出现了意外的结果。
这就是我希望返回的:
sku condition make model derivative height length depth
-------------------------------------------------------------------------------------------
123 new ford test 212 1.28 9.0 4.9
234 new ford test 212 1.28 9.0 4.9
345 new ford test 212 1.28 9.0 4.9
456 new bmw awesome 3.33 3.33
789 new bmw cool 123 2.23 1.99 9.89
987 new bmw cool 123 2.23 1.99 9.89
... ... ... ... ... ... ...
从上面可以看出,SKU 字段是唯一的,但所有其他数据都是基于其他行填充的。这些条件基于条件、制造商、型号、导数,但这些将来可能会发生变化。列名也会定期更改,因此它需要是动态的,而不需要修改查询来添加新列。
如果存在具有相同条件、品牌、型号、导数但高度、长度或深度不同的行,则应保留该值。
抱歉,如果我解释得不够深入。
感谢任何帮助!
谢谢
最佳答案
SELECT sku, condition, make, model, derivative,
IFNULL(t1.height, t2.height) height,
IFNULL(t1.length, t2.length) length,
IFNULL(t1.depth, t2.depth) depth
FROM mytable t1
JOIN (SELECT condition, make, model, derivative,
MAX(height) height, MAX(length) length, MAX(depth) depth
FROM mytable
GROUP BY condition, make, model, derivative) t2
USING (condition, make, model, derivative)
当您添加新列时,它不会自动更新。为此,您必须使用 information_schema
表编写动态 SQL 来获取所有列名称。现在您已经了解了查询的一般结构,我希望您能够自己弄清楚该部分。
关于php - MySQL 分组/合并数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20890139/