Mysql查询返回多列

时间:2013-12-05 07:47:49

标签: mysql sql

我想从5个不同的列中选择并返回一个值。我想

SELECT "BestLoc" from Nutrients WHERE FoodId = '$FoodId' AND CompId = '0000'.
And again where FoodId = '$FoodId' AND CompId = '0001',
And again where FoodId = '$FoodId' AND CompId = '0003',
And again where FoodId = '$FoodId' AND CompId = '0008',
And again where FoodId = '$FoodId' AND CompId = '0130'.

BestLoc返回5次,其中FoodId与输入$ FoodId匹配,以及CompId匹配的5次。

这怎么可能做到简单?最好的方法是在

中返回结果
array(
  [0] => (BestLoc value 1),
  [1] => (BestLoc value 2) and so on..

解决方法如下:

$stack = array();
$stmt = $mysqli->query("SELECT BestLoc from Nutrients WHERE FoodId = '$FoodId' AND CompId IN ('0000', '0001', '0003', '0008', '0130')");
while($return = $stmt->fetch_assoc()){
    array_push($stack, $return['BestLoc']);
}

2 个答案:

答案 0 :(得分:2)

如果我正确地提出您的问题,您似乎只是在寻找IN条款:

SELECT BestLoc from Nutrients
WHERE FoodId = '$FoodId' AND CompId IN ('0000', '0001', '0003', '0008', '0130')

答案 1 :(得分:2)

我认为你在寻找这个?

SELECT BestLoc
 FROM Nutrients
 WHERE FoodId = "$FoodId"
 AND CompId IN ('0000','0001','0003','0008','0130')