输入: Person表: +----------+----------+-----------+ |personId | lastName | firstName | +----------+----------+-----------+ |1 | Wang | Allen | |2 | Alice | Bob | +----------+----------+-----------+ Address表: +-----------+----------+---------------+------------+ |addressId | personId | city | state | +-----------+----------+---------------+------------+ |1 | 2 | New York City | New York | |2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ 输出: +-----------+----------+---------------+----------+ |firstName | lastName | city | state | +-----------+----------+---------------+----------+ |Allen | Wang | Null | Null | |Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ 解释: 地址表中没有personId = 1 的地址,所以它们的城市和州返回 null。 addressId = 1 包含了 personId = 2 的地址信息。
CodeDemo
1 2 3 4 5 6
select firstName, lastName, city, state from Person p leftjoin Address a on p.personId = a.personId
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
CodeDemo
1 2 3 4 5 6 7 8 9 10
# 使用自连接查询, 查询方式为多个where条件 select distinct t1.Num as ConsecutiveNums # 这里如果写count的话在没有数据的测试用例会出现0, 与预期的空不符合,因此写t1.Num并去重比较合理 from Logs t1, Logs t2, Logs t3 where t1.Num = t2.Num and t1.Num = t3.Num and t1.Id +1= t2.Id and t2.Id +1= t3.Id
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | salary | int | | managerId | int | +-------------+---------+ Id是该表的主键。 该表的每一行都表示雇员的ID、姓名、工资和经理的ID。
编写一个SQL查询来查找收入比经理高的员工。
以 任意顺序 返回结果表。
CodeDemo
1 2 3 4
select e1.name as Employee from Employee e1 join Employee e2 on e1.managerId = e2.id where e1.salary > e2.salary
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id 是该表的主键列。 此表的每一行都包含一封电子邮件。电子邮件不包含大写字母。
编写一个 SQL 查询来报告所有重复的电子邮件。 请注意,可以保证电子邮件字段不为 NULL。
以 任意顺序 返回结果表。
CodeDemo
1 2 3 4 5 6 7 8
select email as email from ( select email, count(*) as cnt from Person groupby email ) tmp where cnt >1;