2015-05-25 86 views
0

您好我有這個下表..如何使用字符串和int值

offer_number  training_title 
************** 
    ABC-1   SEMINAR 
    ABC-9   SEMINAR 
    ABC-10   SEMINAR 
    ABCD-9   TRAINING 
    EFGH-9   TESTING 
    EFGH-10  TESTING 

Mysql的

SELECT *, MAX(offer_number) as offer_number_latest FROM (`training_program`) WHERE `training_title` LIKE '%SEMINAR%' GROUP BY `training_title` ORDER BY `offer_number` desc 

我想製作ABC-10 但 我總是得到ABC-選擇馬克斯9而不是ABC-10。

示例2:

SELECT *, MAX(offer_number) as offer_number_latest FROM (`training_program`) WHERE `training_title` LIKE '%TESTING%' GROUP BY `training_title` ORDER BY `offer_number` desc 

我需要的結果EFGH-10 但 我總是EFGH-9不是EFGH-10。

+0

9> 1 - 你就必須有「ABC-09」進行比較,以工作的方式..相反,你可以「提取」從字符串的數量和使用 - 簡單的應該是「REPLACE(offer_number ,'ABC-','')「只獲取字符串的數字部分([或使用udf正則表達式?](http://stackoverflow.com/a/986870/1786423)),然後您可能必須CAST()表示數字(或加上+0使用自動轉換) – jkavalik

+0

是字符前綴總是每組相同? –

+0

freddy?上面的任何輸入? –

回答

1

如果offer_number前綴始終是每training_title相同,下面的(骯髒)的查詢將工作:

select training_title, 
    concat(
    left(offer_number, 
     locate('-', offer_number) 
    ), 
    max(
     cast(substring(offer_number, locate('-', offer_number) + 1) as signed) 
    ) 
) from offers group by training_title 

demo here

-1

MySQL也有字符串函數。

mysql> select * from offer; 
    +--------------+----------------+ 
    | offer_number | training_title | 
    +--------------+----------------+ 
    | ABC-1  | SEMINAR  | 
    | ABC-9  | SEMINAR  | 
    | ABC-10  | SEMINAR  | 
    | ABC-8  | SEMINAR  | 
    | ABC-14  | SEMINAR  | 
    | ABC-12  | SEMINAR  | 
    +--------------+----------------+ 
    6 rows in set (0.00 sec) 

    mysql> SELECT MAX(CAST(SUBSTRING(offer_number,LOCATE('-',offer_number)+1) AS SIGNED)) as MAX FROM offer ; 
    +------+ 
    | MAX | 
    +------+ 
    | 14 | 
    +------+ 
    1 row in set (0.00 sec) 

    mysql> SELECT * FROM offer ORDER BY CAST(SUBSTRING(offer_number,LOCATE('-',offer_number)+1) AS SIGNED); 
    +--------------+----------------+ 
    | offer_number | training_title | 
    +--------------+----------------+ 
    | ABC-1  | SEMINAR  | 
    | ABC-8  | SEMINAR  | 
    | ABC-9  | SEMINAR  | 
    | ABC-10  | SEMINAR  | 
    | ABC-12  | SEMINAR  | 
    | ABC-14  | SEMINAR  | 
    +--------------+----------------+ 
    6 rows in set (0.00 sec) 
相關問題