SQL查询排序:如何让默认地址优先显示及解决语法错误
SQL排序语法错误解决:关键字字段引发的问题
原始查询及结果
执行以下PHP查询代码:
$sql = "SELECT * FROM addresses WHERE user='$userid'";
查询结果如下:
| id | address | default |
|---|---|---|
| 1 | address1 | no |
| 2 | address2 | no |
| 3 | address3 | no |
| 4 | address4 | yes |
| 5 | address5 | no |
| 6 | address6 | no |
需求
需要将default字段值为yes的记录(始终仅一条)优先显示,期望结果如下:
| id | address | default |
|---|---|---|
| 4 | address4 | yes |
| 1 | address1 | no |
| 2 | address2 | no |
| 3 | address3 | no |
| 5 | address5 | no |
| 6 | address6 | no |
错误尝试及报错信息
尝试执行以下SQL语句时触发语法错误:
$sql = "SELECT * FROM addresses WHERE user='$userid' ORDER BY FIELD(default,'yes')";
错误提示:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''yes')' at line 1
解决方法
经@Jens建议,由于default是SQL关键字,将该列重命名为defaultaddress后,问题成功解决。
内容的提问来源于stack exchange,提问作者AbleInfosoft Gmail
相关产品推荐
相关产品推荐

