如何为子句中的sql压缩数组值?

时间:2018-05-15 07:56:02

标签: php mysql

我有一系列水果。我试图在“fruits”列中获取包含这三种水果中任何一种的所有行

$fruits = array('apple','banana','orange');

$imploded_fruits = implode(',',$fruits); 

$sql = "SELECT * FROM market WHERE fruits IN ('$imploded_fruits');";

这不会返回预期值。 格式是否正确?

3 个答案:

答案 0 :(得分:2)

使用select parts.PartNo , coalesce(FirstSale.Total, 0) - coalesce(LastSale.Total, FirstSale.Total, 0) as Sold , (coalesce(FirstSale.Total, 0) - coalesce(LastSale.Total, FirstSale.Total, 0)) * coalesce(LastSale.Retail - LastSale.Wholesale, 0) as Profit from ( select PartNo , max(case when Date < '2018-05-13' then Date end) as FirstEntry , max(case when Date <= '2018-05-14' then Date end) as LastEntry from Sales group by PartNo ) parts left join Sales FirstSale on FirstSale.PartNo = parts.PartNo and FirstSale.Date = parts.FirstEntry left join Sales LastSale on LastSale.PartNo = parts.PartNo and LastSale.Date = parts.LastEntry

implode("','",$fruits)

您的查询将如下所示

https://eval.in/1004169

$fruits = array('apple','banana','orange');
$imploded_fruits = implode("','",$fruits); 
$sql = "SELECT * FROM market WHERE fruits IN ('$imploded_fruits');";

答案 1 :(得分:1)

<?php


$fruits = array('apple','banana','orange');
$imploded_fruits = "'" . implode("','", $fruits) . "'";

$sql = "SELECT * FROM market WHERE fruits IN (" . $imploded_fruits. ");";

echo $sql;

此查询适合您。你错误地使用了引号。你可以在这样的场合做什么(至少我做的是)回应你的查询以查看它的格式。

sql查询的输出是:

SELECT * FROM market WHERE fruits IN ('apple','banana','orange');

答案 2 :(得分:0)

$fruits = array('apple','banana','orange');
$imploded_fruits = join("','",$fruits); 
$sql = "SELECT * FROM market WHERE fruits IN ('$imploded_fruits');";