我可以只选择MYSQL中的一列而不是全部,以使其更快吗? [英] Can I just SELECT one column in MYSQL instead of all, to make it faster?

查看:70
本文介绍了我可以只选择MYSQL中的一列而不是全部,以使其更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....

因为我想要的只是与用户名相对应的用户ID.

Because all I want is the user ID that corresponds to the username.

通常的方法是:

$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
    $the_user_id= $row['userid'];

但是有什么更有效的方法吗? 非常感谢,问候

But is there something more efficient that this? Thanks a lot, regards

推荐答案

您已经把钉子钉在了头上:您想要做的是SELECT userid FROM users WHERE username='$username'.尝试一下-它将起作用:)

You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)

SELECT *几乎总是一个坏主意;最好指定要MySQL返回的列的名称.当然,您仍然需要使用mysql_fetch_assoc或类似的方法来将数据实际获取到PHP变量中,但是至少这节省了MySQL发送所有您将不会使用的列的开销.

SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.

顺便说一句,您可能想使用较新的mysqli库或PDO.与不推荐使用的旧mysql库相比,它们的效率也高得多.

As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.

这篇关于我可以只选择MYSQL中的一列而不是全部,以使其更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆