mysql怎么选中多行,如何从mysql的列中选择多个记录(行)?

博客讨论了在尝试从数据库中选取多个item_name时遇到的问题。使用IN查询与OR查询的效率比较,指出IN查询在处理大量数据时更优。问题出在PHP代码的实现上,由于没有正确迭代结果集,导致只显示了一个item_name。解决方案是使用循环遍历所有结果。
摘要由CSDN通过智能技术生成

I want to display four (4) items'name from these id:

Can I do like this?

SELECT item_name from items WHERE item_id IN ('001', '012', '103', '500')

or

SELECT item_name from items WHERE item_id = '001' or item_id = '012' or item_id = '103' or item_id = '500'

IN RESPONSE TO ALL ANSWERS

Well, most of the answers said it works, but it does not really work. Here is my code:

$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;

The item_id is alphanumeric.

解决方案

You can do either one, but the IN query is much more efficient for this purpose for any large queries. I did some simple testing long ago that revealed it's about 10 times faster to use the IN construct for this. If you're asking if the syntax is correct then yes, it looks fine, other than missing semi-colons to complete the statement.

EDIT: It looks like the actual question you were asking was "why do these queries only return one value". Well, looking at the sample code you posted, the problem is here:

$fetch = mysql_fetch_assoc($result) or die (mysql_error());

$itemsCollected = $fetch['item_name'];

echo $itemsCollected;

You need to loop through and iterate until there are no more results to be fetched, as Pax pointed out. See the PHP manual page for mysql_fetch_assoc:

$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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值