如何将数组放入SQL?

时间:2014-03-24 22:57:04

标签: php mysql sql

我有以下php代码从数据库中获取数字列表:

  $current_product_id = "SELECT `product_id`,`category_id` FROM `oc_product_to_category` WHERE `product_id`='$product_id' ";   
  $current_product_ids = mysql_query($current_product_id); 

  $current_product_cat_ids='';

  while($current_product_cat_id = mysql_fetch_array($current_product_ids)){
$current_product_cat_ids.=$current_product_cat_id['category_id'].',';
}
  echo $current_product_cat_ids;

代码回声如下:84,109,140,146,151,152,

我现在想把这些数字中的每一个都用在另一个SQL查询中,如下所示:

$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path` WHERE `category_id`='84,109,140,146,151,152'"

所以我可以将值放入另一个SQL Query中。我有什么想法可以做到这一点?感谢

4 个答案:

答案 0 :(得分:2)

标准SQL提供IN运算符以匹配值列表。

SELECT `category_id`,`path_id`
FROM `oc_category_path`
WHERE `category_id` IN (84,109,140,146,151,152)

如果值来自表,则子查询是一种特别有用的技术;

SELECT `category_id`,`path_id`
FROM `oc_category_path`
WHERE `category_id` IN (SELECT `cat_id` FROM cat_table WHERE active=true)

答案 1 :(得分:1)

你很亲密。您可以使用MySQL的FIND_IN_SET()IN()

$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path` 
    WHERE  FIND_IN_SET(`category_id`, '84,109,140,146,151,152')"

IN()

$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path` 
    WHERE `category_id` IN(84,109,140,146,151,152)"

答案 2 :(得分:1)

SELECT 
   `category_id`
 , `path_id`
FROM `oc_category_path`
WHERE `category_id` IN(84,109,140,146,151,152)

OR:

SELECT 
   `category_id`
 , `path_id`
FROM `oc_category_path`
WHERE FIND_IN_SET(`category_id`, '84,109,140,146,151,152')

第一个没有引号,第二个引号包含逗号分隔列表的字符串。

答案 3 :(得分:0)

使用IN子句和相同的变量:

$res = mysql_query("SELECT `category_id`,`path_id` FROM `oc_category_path` WHERE `category_id` IN (" . rtrim($current_product_cat_ids, ',') . ")");
while ($row = mysql_fetch_assoc($res)) {
    print_r($row);
}