2012-01-31 55 views
2
I have the following table with two columns 

    ID    Name 
    1    ABC    
    2    Acc   
    3    Bcc 
    4    Bdc 
    5    Cdd 
    6    Cvv 

的柯坪跟蹤查詢是否可以準備一個MySQL查詢,這樣我可以按以下格式從數據庫 得到的結果mysql命令用字母

ID    Name   Alphabet 
    1    ABC    A 
    2    Acc    A 
    3    Bcc    B 
    4    Bdc    B 
    5    Cdd    C 
    6    Cvv    D 

回答

3
SELECT id, `Name`, UPPER(LEFT(Name,1)) AS `alphabet` FROM `mytable` ORDER BY `Name`; 

應該這樣做。

如果大寫字母給你的麻煩,你可以使用:

SELECT id, `Name`, UPPER(LEFT(Name,1)) AS `alphabet` FROM `mytable` ORDER BY LOWER(`Name`); 
2
SELECT ID, Name, substr(Name, 1, 1) as Alphabet 
FROM yourTable 
ORDER BY Name asc 
+0

我認爲'substr'語法是'SUBSTR(STR,POS, LEN)'。 – 2012-01-31 11:13:02

+0

這也是一個有效的語法。兩個作品。我只是確認它而已。 – 2012-01-31 11:17:33

+0

語法'SUBSTR(str,pos)'意味着'SUBSTR(str,pos,LENGTH(str))'。 – 2012-01-31 11:19:07

1

嘗試:

SELECT id, name, LEFT(name, 1) AS alphabet FROM your_table WHERE 1 ORDER BY name 
+0

爲什麼'ORDER BY名字,字母'而不只是'ORDER BY name'? – 2012-01-31 11:17:54