1

I have a problem with sql query in php:

select
    user, name, outlet, switch, port, vlan, mac, status
from access where 
    user like '%'
    and name like '%'
    and outlet like '%'
    and switch like '%'
    and port like '%'
    and vlan like '%'
    and mac like '%'
    and status like '%'
order by 'user';

When running query on MySQL client version: 5.1.36 query doesn't work totally (ORDER BY won't work), however when running SAME query on MySQL client version: 4.1.13, ORDER BY works!

I have checked nearly all manuals about ORDER BY, WHERE, LIKE commands, but no result. No mention about version differences, etc..

4

2 回答 2

2

您必须从子句user中删除引号。ORDER BY这就是导致ORDER BY无法按预期工作的原因,因为您可以在ORDER BY子句中使用任何表达式,并且'user'引号被视为表达式(常量)而不是列名。

测试用例(MySQL 5.1.45):

CREATE TABLE tb (id int);

INSERT INTO tb VALUES (5);
INSERT INTO tb VALUES (1);
INSERT INTO tb VALUES (4);
INSERT INTO tb VALUES (2);
INSERT INTO tb VALUES (3);

SELECT * FROM tb ORDER BY 'id';
+------+
| id   |
+------+
|    5 |
|    1 |
|    4 |
|    2 |
|    3 |
+------+
5 rows in set (0.00 sec)

SELECT * FROM tb ORDER BY id;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
+------+
5 rows in set (0.00 sec)
于 2010-07-29T07:12:22.937 回答
1

I think what you need is:

SELECT `user`,`name`,`outlet`,`switch`,`port`,`vlan`,`mac`,`status` 
FROM `access`
WHERE `user` like '%' 
    AND `name` like '%'
    AND `outlet` like '%'
    AND `switch` like '%'
    AND `port` like '%'
    AND `vlan` like '%'
    AND `mac` like '%'
    AND `status` like '%' 
ORDER BY `user`;

Though I don't understand your WHERE clause. It doesn't filter on any of the fields. EDIT; some of your column names (user, name, port and status) could be MySQL keywords. Try enclosing them in grave accents (`) (I added them to my post as well).

于 2010-07-29T07:08:56.613 回答