在 MySQL 中排名客戶:實用指南
MySQL 不提供內建排名功能,需要自訂查詢來按年齡和性別對客戶進行排名。 本指南示範了一種使用使用者定義變數進行高效排名的解決方案。
查詢:
此查詢使用變數來分配排名:
<code class="language-sql">SELECT first_name, age, gender, @curRank := @curRank + 1 AS rank FROM person p, (SELECT @curRank := 0) r ORDER BY age;</code>
最聰明的部分是(SELECT @curRank := 0) r
子查詢。這優雅地初始化了排名變數 @curRank
,無需單獨的 SET
語句。
範例:
讓我們考慮一個範例person
表:
<code class="language-sql">CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1)); INSERT INTO person VALUES (1, 'Bob', 25, 'M'); INSERT INTO person VALUES (2, 'Jane', 20, 'F'); INSERT INTO person VALUES (3, 'Jack', 30, 'M'); INSERT INTO person VALUES (4, 'Bill', 32, 'M'); INSERT INTO person VALUES (5, 'Nick', 22, 'M'); INSERT INTO person VALUES (6, 'Kathy', 18, 'F'); INSERT INTO person VALUES (7, 'Steve', 36, 'M'); INSERT INTO person VALUES (8, 'Anne', 25, 'F');</code>
查詢結果:
執行查詢會產生以下排名的客戶資料:
<code>+------------+------+--------+------+ | first_name | age | gender | rank | +------------+------+--------+------+ | Kathy | 18 | F | 1 | | Jane | 20 | F | 2 | | Nick | 22 | M | 3 | | Bob | 25 | M | 4 | | Anne | 25 | F | 5 | | Jack | 30 | M | 6 | | Bill | 32 | M | 7 | | Steve | 36 | M | 8 | +------------+------+--------+------+</code>
這清楚地顯示了按年齡排名的顧客。 要將性別納入排名,只需調整 ORDER BY
子句以將性別納入輔助排序標準(例如 ORDER BY age, gender
)。
以上是如何在MySQL中按年齡和性別對客戶進行排名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!