在MySQL命令行客户端中运行以下查询时,我遇到了一些奇怪的行为:
SELECT favoriteGenre, firstName, lastName
FROM members
ORDER BY favoriteGenre, firstName;
我得到以下结果:
favoriteGenre firstName lastName
crime Jane Field
crime John Sparks
horror Marty Pareene
thriller Mary Newton
romance Jo Scrivener
sciFi Nick Blakeley
nonFiction Bill Swan
然而我期待这些结果:
favoriteGenre firstName lastName
crime Jane Field
crime John Sparks
horror Marty Pareene
nonFiction Bill Swan
romance Jo Scrivener
sciFi Nick Blakeley
thriller Mary Newton
请注意nonFiction
位于第7位,而我预计它会是第4位......
这用于创建表的SQL:
USE mydatabase;
CREATE TABLE members (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(30) BINARY NOT NULL UNIQUE,
password CHAR(41) NOT NULL,
firstName VARCHAR(30) NOT NULL,
lastName VARCHAR(30) NOT NULL,
joinDate DATE NOT NULL,
gender ENUM( 'm', 'f' ) NOT NULL,
favoriteGenre ENUM( 'crime', 'horror', 'thriller', 'romance', 'sciFi', 'adventure', 'nonFiction' ) NOT NULL,
emailAddress VARCHAR(50) NOT NULL UNIQUE,
otherInterests TEXT NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO members VALUES( 1, 'sparky', password('mypass'), 'John', 'Sparks', '2007-11-13', 'm', 'crime', 'jsparks@example.com', 'Football, fishing and gardening' );
INSERT INTO members VALUES( 2, 'mary', password('mypass'), 'Mary', 'Newton', '2007-02-06', 'f', 'thriller', 'mary@example.com', 'Writing, hunting and travel' );
INSERT INTO members VALUES( 3, 'jojo', password('mypass'), 'Jo', 'Scrivener', '2006-09-03', 'f', 'romance', 'jscrivener@example.com', 'Genealogy, writing, painting' );
INSERT INTO members VALUES( 4, 'marty', password('mypass'), 'Marty', 'Pareene', '2007-01-07', 'm', 'horror', 'marty@example.com', 'Guitar playing, rock music, clubbing' );
INSERT INTO members VALUES( 5, 'nickb', password('mypass'), 'Nick', 'Blakeley', '2007-08-19', 'm', 'sciFi', 'nick@example.com', 'Watching movies, cooking, socializing' );
INSERT INTO members VALUES( 6, 'bigbill', password('mypass'), 'Bill', 'Swan', '2007-06-11', 'm', 'nonFiction', 'billswan@example.com', 'Tennis, judo, music' );
INSERT INTO members VALUES( 7, 'janefield', password('mypass'), 'Jane', 'Field', '2006-03-03', 'f', 'crime', 'janefield@example.com', 'Thai cookery, gardening, traveling' );
幕后真的发生了什么,以及这种排序是如何完成的?这种行为只对MySQL有用吗?
答案 0 :(得分:4)
favoriteGenre
是一个enum
,而不是我们大多数人期待看到的文字字段。
正如您在documentation中所读到的那样,enum
按其索引排序,而不是按其文本表示排序。这使您的查询结果正确。
要按其值enum
排序,您需要使用CAST(col AS CHAR)
(感谢McAdam331添加此内容,另请参阅他的SQLFiddle)。我会建议您对数据库进行适当的规范化。
答案 1 :(得分:3)
它将首先按第一列对结果进行排序,如果一种类型中有多个结果,则在您的情况下它是犯罪;它将在第二个定义的列的基础上排序。
首先,它会将favoriteGenre排序,然后按名字
排序你的情况是enum,所以它改变了整个游戏。它只会与它的索引相关。因此,你得到了这种奇怪的行为。
希望它能解释