我有这个表:
+---------+----------+
+ Items + Person +
+---------+----------+
+ 2,99,75 + Jack +
+ 4,9,63 + Rose +
+---------+----------+
现在我做一个简单的
LIKE :items
并使用
绑定 $stmt->bindParam(':items',$item,PDO::PARAM_STR);
,
$item = "%9%"
.
结果包含Jack和Rose,这是错误的,因为我希望只有Rose作为我的结果。似乎LIKE
同时看到99和9。我怎么能限制我的LIKE
只有9,因为这是$items
的值?
其他答案也不错。然而,我基于Items似乎是ID的事实提出了这个替代方案。
如果您需要查询逗号分隔的值,我建议使用单独的表。在单个字段中使用LIKE查询永远不会真正做到万无一失,并且可能存在安全问题。试试这个。
表1:Person+---------+----------+
+ ID + Person +
+---------+----------+
+ <int> + <string> +
+---------+----------+
表2:Item
+---------+----------+
+ PersonID+ ItemID +
+---------+----------+
+ <int> + <int> +
+---------+----------+
然后根据需要使用连接来查询两个表。
SELECT * FROM Person INNER JOIN Items ON Items.PersonID = Person.ID
WHERE Items.ItemID = '9';
这将为您提供Person
中与ItemID
"9"相关联的所有记录。
可能会有帮助:http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
这是因为%代表一个或多个字符(任何字符)。所以99将匹配"%9%"
如果您只想要9,您可以尝试使用
"%,9,%"
我认为这里的主要问题是@interrobang所说的,您表示数据的方式。
如果您显示的这个表X是每个人的列表项目,那么您应该有一个包含个人id的列和另一个包含项目id的列,并且有多个行来表示每个人的多个项目。这样做你的搜索会更快,更容易使用和维护在未来。
SQL小提琴MySQL 5.5.30 Schema Setup:CREATE TABLE person (
id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE item (
id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE person_item (
id int auto_increment primary key,
person_id int,
item_id int
);
ALTER TABLE person_item ADD UNIQUE (person_id,item_id);
INSERT INTO person(id,name) VALUES
(1, 'John'),
(2, 'Mary'),
(3, 'Oliver');
INSERT INTO item (id,name) VALUES
(1,'Pen'),
(2,'Pencil'),
(3,'Book');
INSERT INTO person_item (person_id,item_id) VALUES
(1,1),
(1,3),
(2,2),
(3,1);
查询1 :
select p.name from person_item pi, person p, item i
where pi.person_id = p.id
and pi.item_id = i.id
and i.name LIKE 'Book%'
结果:
| NAME |
--------
| John |