1、使用唯一标识码替换员工ID
sql"># Write your MySQL query statement below
SELECT b.unique_id, a.name
FROM Employees as a
LEFT JOIN EmployeeUNI as b
ON a.id = b.id;
2、产品销售分析 I
sql"># Write your MySQL query statement below
SELECTp.product_name, s.year, s.price
FROM Sales s
JOINProduct p
ONs.product_id = p.product_id
总结
- INNER JOIN:仅返回匹配的记录。
- LEFT JOIN:返回左表的所有记录,即使右表没有匹配的记录。
- RIGHT JOIN:返回右表的所有记录,即使左表没有匹配的记录。
- FULL JOIN:返回左表和右表的所有记录,没匹配的部分用
NULL
填充。 - CROSS JOIN:返回两张表的笛卡尔积,生成所有可能的组合。
- SELF JOIN:将表与自身进行连接,常用于表示层级关系。
- NATURAL JOIN:自动根据同名列进行连接。
在MySQL中,JOIN操作默认使用的是INNER JOIN。INNER JOIN是MySQL默认的JOIN类型。它返回两个表中符合条件的行。INNER JOIN使用ON关键字来指定连接条件,将两个表中符合条件的记录合并在一起,生成一个新的结果集。
3、进店却未进行过交易的顾客
sql"># Write your MySQL query statement below
SELECTv.customer_id,count(v.customer_id)count_no_trans
FROMVisits v
LEFT JOIN Transactions t
ON v.visit_id = t.visit_id
WHEREtransaction_id is NULL
GROUP BYv.customer_id
4、上升的温度
sql">SELECT a.id
FROM Weather as a
CROSS JOINWeather as b
WHEREdatediff(a.recordDate,b.recordDate) = 1
ANDa.Temperature >b.Temperature
5、每台机器的进程平均运行时间
sql"># Write your MySQL query statement below
SELECTmachine_id, round(sum(if(activity_type = 'start', -timestamp, timestamp)) / count(*)*2, 3) as processing_time
FROM Activity
GROUP BYmachine_id
6、员工奖金
sql"># Write your MySQL query statement below
SELECTe.name, b.bonus
FROM Employee e
LEFT JOINBonus b
ONe.empId = b.empId
WHEREb.bonus is NULL OR b.bonus < 1000
7、学生们参加各科测试的次数
sql">SELECT s.student_id, s.student_name, sub.subject_name, IFNULL(grouped.attended_exams, 0) AS attended_exams
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN (SELECT student_id, subject_name, COUNT(*) AS attended_examsFROM ExaminationsGROUP BY student_id, subject_name
) grouped
ON s.student_id = grouped.student_id AND sub.subject_name = grouped.subject_name
ORDER BY s.student_id, sub.subject_name;
8、至少有5名直接下属的经理
sql"># Write your MySQL query statement below
SELECT b.name
FROM Employee a
LEFT JOINEmployee b
ON a.managerId = b.id
GROUP BYa.managerId
HAVING COUNT(b.id)>=5
9、确认率
sql"># Write your MySQL query statement below
SELECTT1.user_id,round(count(if(T2.action = "confirmed",true,null)) / count(*),2) AS confirmation_rate
FROMSignups as T1
JOIN confirmations AS T2
ON T1.user_id = T2.user_id
GROUP BYT1.user_id;