作者:mobiledu2502924121 | 来源:互联网 | 2024-11-20 14:44
在SQL查询中,有时需要根据部分匹配或动态生成的字符串条件来筛选数据。下面的示例展示了如何使用LIKE和CONCAT函数来实现这一需求,并同时处理多个表之间的联接和数据聚合。
以下是具体的SQL语句:
SELECT
(@i := @i + 1) AS number,
x.uuid,
x.payment_code,
x.supplier_name,
x.receive_money,
x.is_export_flag,
x.export_time,
x.payer,
x.region_name,
x.user_name,
x.marketer_id,
x.region_id
FROM
(
SELECT DISTINCT
a.uuid,
a.payment_code,
a.supplier_name,
a.receive_money,
CASE
WHEN a.is_export_flag = 0 THEN '未导出'
ELSE '已导出'
END AS is_export_flag,
a.export_time,
b.payer,
d.region_name,
GROUP_CONCAT(DISTINCT f.user_name SEPARATOR ', ') AS user_name,
e.marketer_id,
d.uuid AS region_id
FROM
biz_lc_payment_info a
INNER JOIN biz_lc_payment_invoice_info b ON a.payment_id = b.payment_id
LEFT JOIN biz_item_company c ON b.payer = c.item_company_name AND c.sys_status = 1
LEFT JOIN biz_item_region d ON c.region_id = d.uuid AND d.sys_status = 1
LEFT JOIN biz_link_marketer_region e ON e.region_id = d.uuid AND d.sys_status = 1
LEFT JOIN sys_user f ON e.marketer_id LIKE CONCAT('%', f.uuid, '%') AND f.sys_status = 1
WHERE
a.sys_status = 1
AND b.sys_status = 1
GROUP BY
a.uuid
) x,
(SELECT @i := 0) AS y
WHERE
x.is_export_flag = '已导出'
上述SQL查询首先通过子查询从多个表中选择和聚合所需的数据,然后在外层查询中为每条记录添加一个行号(number)。子查询中的GROUP_CONCAT函数用于将多个用户的名称合并成一个字符串,而LIKE与CONCAT的结合则用于灵活地匹配marketer_id字段中的部分值。最后,外层查询还通过WHERE子句过滤了已导出的数据。