1、题目要求(175、combine two tables):
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people(注意后面这句话,所以应该是左联结)
解答:SELECT Person.FirstName, Person.LastName, Address.City, Address.State
FROM Person LEFT OUTER JOIN Address
ON Person.PersonId = Address.PersonId
2、题目要求(176. Second Highest Salary):
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.
1) UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
2) SELECT语句的ORDER BY 子句对检索出的数据进行排序,ORDER BY语句必须是SELECT语句的最后一条子句。
3)错误类型:Every derived table must have its own alias。摘自:http://blog.sina.com.cn/s/blog_5d2eee260100xu8b.html
这句话的意思是说每个派生出来的表都必须有一个自己的别名,一般在多表查询时,会出现此错误。
因为,进行嵌套查询的时候子查询出来的的结果是作为一个派生表来进行上一级的查询的,所以子查询的结果必须要有一个别名
把MySQL语句改成:select count(*) from (select * from ……) as total;
问题就解决了,虽然只加了一个没有任何作用的别名total,但这个别名是必须的
# Write your MySQL query statement below
SELECT Salary AS SecondHighestSalary FROM
(SELECT DISTINCT Salary FROM Employee
UNION
SELECT null FROM Employee WHERE Salary IS NULL) AS total
ORDER BY Salary DESC LIMIT 1 OFFSET 1 (这个是错误的,对于不存在的第二个薪酬不能返回null,对null理解错误)
正确答案是: select(select salary from Employee group by salary order by salary desc limit 1,1) as 'SecondHighestSalary';
需要使用两个select,第二个select用于重建列和列值。因为second highest salary 如果不存在的话,那么内部的select返回值是null
更严谨一点的写法:(摘自:http://blog.csdn.net/yeruby/article/details/47748165)
- 1
注意mysql语法的IFNULL关键字的用法:
- 1
- 2