我想从这些id中显示四(4)项的名称:我可以这样做吗?
SELECT item_name from items WHERE item_id IN ('001', '012', '103', '500')
要么
SELECT item_name from items WHERE item_id = '001' or item_id = '012' or item_id = '103' or item_id = '500'
响应所有答案
好吧,大多数答案说它有效,但它确实不起作用.这是我的代码:
$query = "SELECT `item_name` from items WHERE item_id IN('s001','a012','t103','p500')"; $result = mysql_query($query, $conn) or die (mysql_error()); $fetch = mysql_fetch_assoc($result) or die (mysql_error()); $itemsCollected = $fetch['item_name']; echo $itemsCollected;
这item_id
是字母数字.
您可以执行任一操作,但对于任何大型查询,IN查询都可以更有效地实现此目的.我很久以前做了一些简单的测试,发现使用IN构造的速度要快10倍.如果你问的是语法是否正确,那么它看起来很好,除了缺少分号以完成语句.
编辑:看起来你问的实际问题是"为什么这些查询只返回一个值".那么,看看你发布的示例代码,问题出在这里:
$fetch = mysql_fetch_assoc($result) or die (mysql_error()); $itemsCollected = $fetch['item_name']; echo $itemsCollected;
Pax指出,你需要循环并迭代,直到没有更多的结果被提取.请参阅mysql_fetch_assoc的PHP手册页:
$sql = "SELECT item_name from items WHERE item_id IN('s001','a012')"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } // While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } mysql_free_result($result);