我遇到了下面的查询,使用 Mysql 将行动态转换为列。有谁知道 Product_Name 字段前后的 3 个单引号的作用?
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'count(case when Product_Name = ''',
Product_Name,
''' then 1 end) AS ',
replace(Product_Name, ' ', '')
)
) INTO @sql
from products;
SET @sql = CONCAT('SELECT pt.partner_name, ', @sql, ' from partners pt
left join sales s
on pt.part_id = s.partner_id
left join products pd
on s.product_id = pd.prod_id
group by pt.partner_name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
最佳答案
https://dev.mysql.com/doc/refman/5.7/en/string-literals.html说:
A
'
inside a string quoted with'
may be written as''
.
该手册页上有很多示例。
关于Mysql连续3个单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085299/