MYSQL - 如何进行字符串比较和查询?

时间:2011-02-23 10:44:46

标签: mysql

+--------------------+---------------+------+-----+---------+-------+
| ID                 | GKEY          |GOODS | PRI | COUNTRY | Extra |
+--------------------+---------------+------+-----+---------+-------+
| 1                  | BOOK-1        | 1    | 10  |         |       |
| 2                  | PHONE-1       | 2    | 12  |         |       |
| 3                  | BOOK-2        | 1    | 13  |         |       |
| 4                  | BOOK-3        | 1    | 10  |         |       |
| 5                  | PHONE-2       | 2    | 10  |         |       |
| 6                  | PHONE-3       | 2    | 20  |         |       |
| 7                  | BOOK-10       | 2    | 20  |         |       |
| 8                  | BOOK-11       | 2    | 20  |         |       |
| 9                  | BOOK-20       | 2    | 20  |         |       |
| 10                 | BOOK-21       | 2    | 20  |         |       |
| 11                 | PHONE-30      | 2    | 20  |         |       |
+--------------------+---------------+------+-----+---------+-------+ 

上面是我的桌子。我想得到GKEY>的所有记录。 BOOK-2,谁能用mysql告诉我表达式?

使用“WHERE GKEY>'BOOK-2'”无法获得正确的结果。

2 个答案:

答案 0 :(得分:1)

SELECT * FROM `table` AS `t1` WHERE `t1`.`id` > (SELECT `id` FROM `table` AS `t2` WHERE `t2`.`GKEY`='BOOK-2' LIMIT 1)

答案 1 :(得分:1)

如何(等等):

(这是MSSQL - 我猜它在MySQL中会类似)

select 
   *
from
   (
      select 
         *,
         index = convert(int,replace(GKEY,'BOOK-',''))
      from table
      where 
         GKEY like 'BOOK%'
   ) sub
where
   sub.index > 2

作为解释:内部查询基本上重新创建了您的表,但仅限于BOOK行,并且使用包含右数据类型中的索引的额外列,以比数字比较工作。

或者像这样:

select
   *
from table
where
   (
     case
        when GKEY like 'BOOK%' then
           case when convert(int,replace(GKEY,'BOOK-','')) > 2 then 1
           else 0
           end
        else 0
        end
   ) = 1

基本上问题是你需要在将索引转换成数字之前检查BOOK,因为GKEY的其他值会产生错误(没有做一些笨重的字符串处理)。