Mysql 运行时常见错误解决方法
1、order by和group by先后顺序导致的报错
SELECT
t.id,
t.bed_no AS bedNo
FROM
tb_org_patient t
WHERE
t.is_deleted = 0
AND t.is_enable = 1
AND t.org_id = 111
AND t.is_out_hp = 0
AND t.district_id = 539
AND t.bed_no IS NOT NULL
AND t.bed_no != ''
ORDER BY
t.bed_no ASC
GROUP BY
t.bed_no
- 以上代码执行会报如下错误
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY
t.bed_no' at line 16
- 解决方法
将order放在最后即可
SELECT
t.id,
t.bed_no AS bedNo
FROM
tb_org_patient t
WHERE
t.is_deleted = 0
AND t.is_enable = 1
AND t.org_id = 111
AND t.is_out_hp = 0
AND t.district_id = 539
AND t.bed_no IS NOT NULL
AND t.bed_no != ''
GROUP BY
t.bed_no
ORDER BY
t.bed_no ASC
2、MySQL中union和order by同时使用的实现方法。报错:Incorrect usage of UNION and ORDER BY
MySQL中union和order by是可以一起使用的,但是在使用中需要注意一些小问题,下面通过例子来说明。首先看下面的t1表。
1、如果直接用如下sql语句是会报错:Incorrect usage of UNION and ORDER BY。
SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY score ASC
UNION
SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC
因为union在没有括号的情况下只能使用一个order by,所以报错,这个语句有2种修改方法。如下:
(1)可以将前面一个order by去掉,改成如下:
SELECT * FROM t1 WHERE username LIKE 'l%'
UNION
SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC
该sql的意思就是先union,然后对整个结果集进行order by。如此一来第一条select语句就无法order by 排序
(2)可以通过两个查询分别加括号的方式,改成如下:
(SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY sroce ASC)
UNION
(SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC)
这种方式的目的是为了让两个结果集先分别order by,然后再对两个结果集进行union。如果order by 无效,可改成如下格式:
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY score ASC) t3
UNION
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC) t4
也就是说,order by不能直接出现在union的子句中,但是可以出现在子句的子句中。
2、union 和 union all 的区别
union会过滤掉两个结果集中重复的行,而union all不会过滤掉重复行。
3、union 和 order by 共存的办法
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE 'l%' ) t3
UNION
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE '%m%' ) t4 ORDER BY score ASC
将 ORDER BY 放置在 union 之后
3、Mysql中使用replace uuid()
后主键没有重复却报Duplicate entry '' for key 'PRIMARY'错
- 解决mysql replace uuid() 导致重复的问题
#当字符集设置为utf8mb4时,执行下面SQL时,返回的多条数据中的uuid是相同的值。
SELECT UPPER(REPLACE(uuid(),'-','')) FROM t_user
----------------------------------------------------------------------------------
UPPER(REPLACE(uuid(),'-',''))
52A8B75CEB5D11E5B180005056920044
52A8B75CEB5D11E5B180005056920044
52A8B75CEB5D11E5B180005056920044
52A8B75CEB5D11E5B180005056920044
----------------------------------------------------------------------------------
#解决办法可以是这样,加MD5:
SELECT MD5(uuid()) FROM t_user
4、Mysql中错误码: 1630 FUNCTION count does not exist. Check the 'Function Name Parsing and Resolution' section in
错误码: 1630
FUNCTION count does not exist. Check the'Function Name Parsing and Resolution' section in the Reference Manual
#解决方案:如sum() count() avg这些函数里面是这样子写的sum () sum和()分开了,不是挨着写的,所以报这个错
Q.E.D.