使用数组加入myql查询

时间:2019-02-01 14:05:09

标签: php mysqli

我有这样的mysql表

表测试

| idx|  name  | year | month |
+----+--------+------+-------+
| 1  |  foo-u | 2019 | 1     |
| 2  |  foo-v | 2019 | 2     |
| 3  |  foo-w | 2019 | 3     |
| 4  |  foo-x | 2019 | 1     |
| 5  |  foo-y | 2019 | 2     |
| 6  |  foo-z | 2019 | 3     |

和这样的数组

$qty = array("1"=>"42", "4"=>"44", "5"=>"54"); //result from unserialize data

我怎样才能将mysql query和$ qty数组加入这样的结果

| idx|  name  | year | month |  qty |
+----+--------+------+-------+------+
| 1  |  foo-u | 2019 | 1     |  42  |
| 4  |  foo-x | 2019 | 1     |  44  |
| 5  |  foo-y | 2019 | 2     |  54  |

我试图这样

<?php
foreach ($qty as $quantity=>$value){
    $product .= $quantity.',';  
}
$produk2 = rtrim($product,',');
$sql = "select * from test where idx in ($produk2)";
?>

我如何改善我的SQL查询以在结果中注入数量(数组值) 谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过一些从数组中获取ID和相应数量的“表”联合来做到这一点

select * 
from test 
join 
   (select 1 id, 42 qty 
    union
    select 4 id, 44 qty
    union
    select 5 id, 54 qty) t
using(id)
where idx in (1,4,5)

在PHP代码中

$union = [];
foreach ($qty as $quantity=>$value){
    $union[] = "select $quantity id, $value qty";  
}

$produk2 = implode(',', array_keys(qty));
$subquery = implode(' union ', $union);
$sql = "select * from test  join ($subquery) t using(id) where idx in ($produk2)";