MySQL运算符SELECT如何从类似的行中获得一个精确的行结果?

时间:2015-07-21 16:59:38

标签: php mysql

我在简单的表类别(id,name,seo)中有这样的'SEO'行

"abc"
"abc 22"
"abc 33"

MySQL如何使用此查询

SELECT id FROM categories WHERE seo='abc' AND LENGTH('abc')='3';"

一个确切的行结果“abc”来自“abc”而没有找到“abc 22”和“abc 33”?

2 个答案:

答案 0 :(得分:1)

create table stuff
(   id int auto_increment primary key,
    seo varchar(100) not null
    -- unique key (seo) not a bad idea
);

insert stuff (seo) values ('abc'),('abc7'),('kitty likes abc'),('abc and more abc'),('kittens');
insert stuff (seo) values ('abc at beginning'),('frogs'),('and at the end abc'),('qwertyabcqwerty');


select id from stuff where seo='abc';
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.02 sec)

以下是like的行为:

select * from stuff where seo like '%abc';
+----+--------------------+
| id | seo                |
+----+--------------------+
|  1 | abc                |
|  3 | kitty likes abc    |
|  4 | abc and more abc   |
|  8 | and at the end abc |
+----+--------------------+
4 rows in set (0.00 sec)

select * from stuff where seo like 'abc%';
+----+------------------+
| id | seo              |
+----+------------------+
|  1 | abc              |
|  2 | abc7             |
|  4 | abc and more abc |
|  6 | abc at beginning |
+----+------------------+
4 rows in set (0.00 sec)

select id,seo from stuff where seo like '%abc%';
+----+--------------------+
| id | seo                |
+----+--------------------+
|  1 | abc                |
|  2 | abc7               |
|  3 | kitty likes abc    |
|  4 | abc and more abc   |
|  6 | abc at beginning   |
|  8 | and at the end abc |
|  9 | qwertyabcqwerty    |
+----+--------------------+
7 rows in set (0.00 sec)

答案 1 :(得分:0)

由于您使用的是精确比较运算符,因此您可以使用:

SELECT id FROM categories WHERE seo = 'abc';

由于您使用的是=,因此无需测试长度。