select employee_id from ( select employee_id from employees unionall select employee_id from salaries ) as t groupby employee_id having count(employee_id) =1 orderby employee_id;
select id, 'Root' Type from tree where p_id isnull union select id, 'Inner' Type from tree where id in (selectdistinct p_id from tree) and p_id isnotnull union select id, 'Leaf' Type from tree where id notin (selectdistinct p_id from tree where p_id isnotnull) and p_id isnotnull
A not in B的原理是拿A表值与B表值做是否不等的比较, 也就是a != b. 在sql中, null是缺失未知值而不是空值(详情请见MySQL reference).
当你判断任意值a != null时, 官方说, “You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL”, 任何与null值的对比都将返回null. 因此返回结果为否,这点可以用代码 select if(1 = null, ‘true’, ‘false’)证实.
从上述原理可见, 当询问 id not in (select p_id from tree)时, 因为p_id有null值, 返回结果全为false, 于是跳到else的结果, 返回值为inner. 所以在答案中,leaf结果从未彰显,全被inner取代.
1 2 3 4 5 6 7 8
select id, casewhen p_id isnullthen "Root" when id notin (select p_id from tree where p_id isnotnull) then "Leaf" else "Inner" endas Type from tree
select v.customer_id, count(v.customer_id) count_no_trans from visits v where v.visit_id notin (select visit_id from transactions) groupby v.customer_id
select v.customer_id as customer_id, count(v.customer_id) as count_no_trans from Visits v leftjoin Transactions t on v.visit_id = t.visit_id where transaction_id isnullgroupby v.customer_id;
select u.name, sum(if(r.distance isnotnull, r.distance, 0)) travelled_distance from users u leftjoin rides r on u.id = r.user_id groupby r.user_id orderby travelled_distance desc, u.name
1158. 市场分析 I 思路: 外连接时要注意where和on的区别,on是在连接构造临时表时执行的,不管on中条件是否成立都会返回主表(也就是left join左边的表)的内容,where是在临时表形成后执行筛选作用的,不满足条件的整行都会被过滤掉。如果这里用的是 where year(order_date)=’2019’ 那么得到的结果将会把不满足条件的user_id为3,4的行给删掉。用on的话会保留user_id为3,4的行。
1 2 3
select user_id as buyer_id, join_date, count(order_id) as orders_in_2019 from Users as u leftjoin Orders as o on u.user_id = o.buyer_id andyear(order_date)='2019' groupby user_id
SELECT s.product_id, p.product_name FROM sales s LEFTJOIN product p ON s.product_id = p.product_id GROUPBY s.product_id HAVINGMIN(sale_date) >='2019-01-01' ANDMAX(sale_date) <='2019-03-31';