2
在查詢中使用它之前,可以對值列表進行排序嗎?MySQL:在查詢中使用它之前對值進行排序
贊SELECT SORTINGFN(2,3,1)
並得到1,2,3
? 類似SELECT 2,3,1 ORDER BY ??? ASC
,但按順序排序?
我需要確保的參數總是以相同的順序,從MD5('1,2,3')
和MD5('2,3,1')
在查詢中使用它之前,可以對值列表進行排序嗎?MySQL:在查詢中使用它之前對值進行排序
贊SELECT SORTINGFN(2,3,1)
並得到1,2,3
? 類似SELECT 2,3,1 ORDER BY ??? ASC
,但按順序排序?
我需要確保的參數總是以相同的順序,從MD5('1,2,3')
和MD5('2,3,1')
得到相同的哈希沒有表(設定值argx
):
SELECT arg1,arg2,arg3,
MD5(SELECT GROUP_CONCAT(col ORDER BY col)
FROM (SELECT arg1 AS col
UNION ALL SELECT arg2
UNION ALL SELECT arg3) AS sub) AS md5_checksum
輸出:
╔════╦════╦════╦══════════════════════════════════╗
║ 1 ║ 2 ║ 3 ║ md5_checksum ║
╠════╬════╬════╬══════════════════════════════════╣
║ 1 ║ 2 ║ 3 ║ 55b84a9d317184fe61224bfb4a060fb0 ║
║ 3 ║ 2 ║ 1 ║ 55b84a9d317184fe61224bfb4a060fb0 ║
║ 3 ║ 1 ║ 2 ║ 55b84a9d317184fe61224bfb4a060fb0 ║
╚════╩════╩════╩══════════════════════════════════╝
無論如何MD5
是弱散列算法。
SQL可以做很多事情。問題是這樣的操作的好地方,當你可以在應用層做到這一點。
任意列表:
SELECT MD5(GROUP_CONCAT(val ORDER BY val)) AS md5_sum
FROM (
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.results, ',', n.n), ',', -1) AS val
FROM (SELECT '3,2,1,10,212,3123,1' AS results) AS t
CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
WHERE n.n <= 1 + (LENGTH(t.results) - LENGTH(REPLACE(t.results, ',', '')))
) sub
輸出:
╔══════════════════════╦══════════════════════════════════╗
║ args ║ md5_sum ║
╠══════════════════════╬══════════════════════════════════╣
║ 3,2,1,10,212,3123,1 ║ e2003296ed64cb59be61558275e22433 ║
║ 212,3123,1,3,2,1,10 ║ e2003296ed64cb59be61558275e22433 ║
╚══════════════════════╩══════════════════════════════════╝
我需要的ID從應用程序來與MySQL進行排序。沒有包含該ID的表格,它們只是參數。 是的,我可以在應用程序中對它們進行排序,但也許可以用MySQL,只是爲了好奇。 –
有趣的想法,但ID列表具有任意長度 –
@Kanstantsin問題在哪裏?只需添加更多參數'(SELECT arg1 AS col UNION ALL SELECT arg2 UNION ALL SELECT arg3 UNION ALL ...)' – lad2025