如何在mysql中使用IN运算符


how to use IN operator in mysql

假设我有一个类似以下的表

DealId类别
1 nbsp nbsp nbsp nbsp;衣服
2 nbsp nbsp nbsp nbsp;衣服、鞋子和配件
3 nbsp nbsp nbsp nbsp;鞋子和配件
4 nbsp nbsp nbsp nbsp;珠宝
5 nbsp nbsp nbsp nbsp;服装、珠宝

现在假设我得到了
这样的类别$data['categories']='clothes,Shoes and accessories';

我使用以下代码:

$cat=$_REQUEST['categories'];
$query=mysql_query("select * from Deals where Categories IN ($cat)");
while($row=mysql_fetch_assoc($query))
{
    echo json_encode($row);
}

我得到了一个错误,我还使用了split()函数和其他我没有得到好结果的技术
我需要选择所有具有"衣服"answers"鞋子和配件"的行

您的IN操作员应该是这样的

IN('Clothes','Shoes','accessories','jewelery');

因此$cat变量应该具有根据IN运算符

的值
The IN operator allows you to determine if a specified value matches any one of a list or a subquery

你可以像一样使用它

select * from Deals where Categories IN ('value1','value2' etc)

我认为创建数据库的方式有问题,因为它不尊重第一个正常形式。

http://en.wikipedia.org/wiki/Database_normalization#Normal_forms

此外,IN会将给定值的列表与数据库中字段的整个值进行比较(在您的情况下,例如"衣服、鞋子和配件"),mysql不会解析字符串来查找其中的单词。

http://www.tutorialspoint.com/mysql/mysql-in-clause.htm

我像这样使用Categories&2

你可以试试这个

<?php
$cat=$_REQUEST['categories'];
$catArray=explode(",",$cat);
$sqlSearch='';
foreach($catArray as $onecat) {
    $sqlSearch= ($sqlSearch!=''?' OR':'WHERE ')."Categories LIKE '%".$onecat."%' "; 
}
$cat=str_replace(",","','",$cat);
$query=mysql_query("select * FROM Deals".$sqlSearch);
while($row=mysql_fetch_assoc($query)){
    echo json_encode($row);
}
?>