1、使用唯一标识码替换员工ID
# 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
# Write your MySQL query statement below
SELECT
p.product_name, s.year, s.price
FROM
Sales s
JOIN
Product p
ON
s.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、进店却未进行过交易的顾客
# Write your MySQL query statement below
SELECT
v.customer_id,count(v.customer_id)count_no_trans
FROM
Visits v
LEFT JOIN
Transactions t
ON
v.visit_id = t.visit_id
WHERE
transaction_id is NULL
GROUP BY
v.customer_id
4、上升的温度
SELECT
a.id
FROM
Weather as a
CROSS JOIN
Weather as b
WHERE
datediff(a.recordDate,b.recordDate) = 1
AND
a.Temperature >b.Temperature
5、每台机器的进程平均运行时间
# Write your MySQL query statement below
SELECT
machine_id, round(sum(if(activity_type = 'start', -timestamp, timestamp)) / count(*)*2, 3) as processing_time
FROM
Activity
GROUP BY
machine_id
6、员工奖金
# Write your MySQL query statement below
SELECT
e.name, b.bonus
FROM
Employee e
LEFT JOIN
Bonus b
ON
e.empId = b.empId
WHERE
b.bonus is NULL OR b.bonus < 1000
7、学生们参加各科测试的次数
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_exams
FROM Examinations
GROUP 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名直接下属的经理
# Write your MySQL query statement below
SELECT
b.name
FROM
Employee a
LEFT JOIN
Employee b
ON
a.managerId = b.id
GROUP BY
a.managerId
HAVING
COUNT(b.id)>=5
9、确认率
# Write your MySQL query statement below
SELECT
T1.user_id,round(count(if(T2.action = "confirmed",true,null)) / count(*),2) AS confirmation_rate
FROM
Signups as T1
JOIN
confirmations AS T2
ON
T1.user_id = T2.user_id
GROUP BY
T1.user_id;