我想从id = 4的数据库表中返回字段name
。MYSQL更容易处理哪个查询。
SELECT name, id FROM table WHERE id = 4
或
SELECT name FROM table WHERE id = 4
我想我是在问将 WHERE
语句中的字段也放在 SELECT
中是否是一种好习惯,即使我不会在 php.ini 中返回它也是如此。
最佳答案
SELECT name, id FROM table WHERE id = 4
也会在 mysql 的结果中包含 id,并且它对数据的影响很小,因为它只是一个数字,但是如果您在选择其他内容(例如 SELECT name)的情况下执行此操作, id FROM table WHERE name = "ron"
绝对是一个不好的做法,因为更多的数据正在从数据库服务器传输,因为您已经知道名称“ron”,并且由于它不是唯一的,它可能有不止一行.
mysql> explain select id,name from admin_users where id = 1;
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | admin_users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
mysql> explain select name from admin_users where id = 1;
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | admin_users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
相比于
mysql> explain select id,name from admin_users where name = 'ron';
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | admin_users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
123 row in set (0.11 sec)
mysql> explain select name from admin_users where name = 'ron';
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | admin_users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------------+-------+---------------+---------+---------+-------+------+-------+
123 row in set (0.05 sec)
关于MYSQL select语句中的where字段也一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780694/