一、常用函数

group_concat 函数

用法:group_concat (待拼接对象)
输出:用逗号进行拼接后的字符串

replace 函数

语法:replace(object,search,replace)
意思:把object中出现search的全部替换为replace


二、获取特定列小于某值的记录

想法:
我想获取一个表中的所有记录,直到特定列的总和小于或等于n

例如:

slno item price
1 item1 1000
2 item2 2000
3 item3 3000
4 item4 4000
5 item5 5000
6 item6 6000

我想从上面的表中获取所有记录,直到总和(价格)小于或等于 10000

因此,对于上表,我的结果将是前 4 条记录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//方案一
SELECT slno, item, price
FROM
(
SELECT slno, item, price, @t := @t + price total
FROM table1 CROSS JOIN (SELECT @t := 0) i
ORDER BY slno
) q
WHERE total <= 10000

//方案二
SELECT slno, item, price
FROM
(
SELECT slno, item, price,
(
SELECT SUM(price)
FROM table1
WHERE slno <= t.slno
) total
FROM table1 t
) q
WHERE total <= 10000
ORDER BY slno

三、left join查找和展示count(*)为0的记录

1
2
3
4
5
6
7
8
9
SELECT 
A.policyCode,
IFNULL(B.ZH,0)
FROM (select policyCode from t_warningPolicy) AS A
LEFT JOIN
(
SELECT policyCode,COUNT(*) as ZH FROM t_warning GROUP BY policyCode
) AS B
ON A.policyCode=B.policyCode

四、group by 时出现 only_full_group_by 错误

ANY_VALUE

用法:ANY_VALUE(字段名)

1
2
3
4
5
select
id,
ANY_VALUE(name)
from table
group by id