我很好奇是否/如何编写一个返回表中每行的最大值的查询以及包含该行的列的索引。
CREATE TABLE my_table (
id INT unsigned NOT NULL AUTO_INCREMENT,
field1 INT NOT NULL,
field2 INT NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO my_table (field1, field2) VALUES
(5, 3),
(65, 89),
(4, 4)
查询的所需结果集为
id max_val col_idx
-- ------- -------
1 5 2
2 89 3
3 4 2
(我更喜欢使用value来返回最小的列索引)
答案 0 :(得分:2)
你可以这样做
SELECT id , GREATEST(field1, field2) max_val ,
CASE WHEN field1 >= field2 THEN 2 ELSE 3 END col_idx
FROM my_table
答案 1 :(得分:0)
这将返回每行的最大值..请参阅工作FIDDLE
SELECT
IF (field1 >= field2, field1, field2) AS max_val,
IF (field1 >= field2, 2, 3) AS my_index
FROM my_table
答案 2 :(得分:0)
标准化设计可能如下所示......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT unsigned
,type INT NOT NULL
,val INT NOT NULL
,PRIMARY KEY (id,type)
);
INSERT INTO my_table VALUES
(1,1,5),
(1,2,3),
(2,1,65),
(2,2,89),
(3,1,4),
(3,2,4);
SELECT * FROM my_table;
+----+------+-----+
| id | type | val |
+----+------+-----+
| 1 | 1 | 5 |
| 1 | 2 | 3 |
| 2 | 1 | 65 |
| 2 | 2 | 89 |
| 3 | 1 | 4 |
| 3 | 2 | 4 |
+----+------+-----+
因此......
SELECT x.*
FROM my_table x
LEFT
JOIN my_table y
ON y.id = x.id
AND (y.val > x.val OR (y.val = x.val AND y.type < x.type))
WHERE y.id IS NULL;
+----+------+-----+
| id | type | val |
+----+------+-----+
| 1 | 1 | 5 |
| 2 | 2 | 89 |
| 3 | 1 | 4 |
+----+------+-----+
......或更现代,更快的替代方案。