1. 第一段代码
2. 第二段代码
2.1 题目地址:SQL82 牛客的课程订单分析(六)
SELECT t.id,
t.is_group_buy,
IF(t.is_group_buy = 'Yes', NULL, t.name) AS client_name
FROM (SELECT *,
COUNT(*) OVER(PARTITION BY user_id) AS cnt
FROM order_info o
LEFT JOIN client c
ON o.client_id = c.id
WHERE date > '2025-10-15'
AND status = 'completed'
AND product_name IN ('C++', 'Java', 'Python')
) AS t
WHERE t.cnt >= 2
ORDER BY t.id
2.2 报错
Execution Error
SQL_ERROR_INFO: "Duplicate column name 'id'"
2.3 解释
报错原因是参与子查询中参与JOIN 的两个表存在相同名称的字段,且并非连接字段,即下图的id
2.4 解决
表格中有相同字段对的情况下,在select 字段的时候需要在其前面指定表格名。比如 SELECT xxx 改为SELECT a.xxx
SELECT t.id,
t.is_group_buy,
IF(t.is_group_buy = 'Yes', NULL, t.name) AS client_name
FROM (SELECT o.*, c.name,
COUNT(*) OVER(PARTITION BY user_id) AS cnt
FROM order_info o
LEFT JOIN client c
ON o.client_id = c.id
WHERE date > '2025-10-15'
AND status = 'completed'
AND product_name IN ('C++', 'Java', 'Python')
) AS t
WHERE t.cnt >= 2
ORDER BY t.id
2.5 反思
其实这里问题的根源是我将JOIN 放在了FROM 后面的子查询中,而子查询的SELECT 中使用了全选* ,这是一条新手经验:使用了JOIN ,就要注意对重复字段进行指定表格,包括*
|