[SQL] Advanced query and connection of interview

603 consecutive vacant seats

insert image description here

select distinct c1.seat_id
from Cinema c1
join Cinema c2
on abs(c2.seat_id-c1.seat_id) = 1
where c1.free=1 and c2.free=1
order by c1.seat_id;

Summarize

  • Idea: Why do we need abs and distinct here? If it is the following code, why not?
select c1.seat_id
from Cinema c1
join Cinema c2
on c2.seat_id-c1.seat_id = 1
where c1.free=1 and c2.free=1
order by c1.seat_id;

The result of the above code ignores the last record that meets the condition, so we need to use abs so that we can get all records that meet the condition, but there are duplicate records, so we need to use distinct to deduplicate elements.

1795 Prices of each product in different stores

insert image description here

# Write your MySQL query statement below
select product_id, 'store1' as store, store1 as price from Products where store1 is not null
union all
select product_id, 'store2' as store, store2 as price from Products where store2 is not null
union all
select product_id, 'store3' as store, store3 as price from Products where store3 is not null

Summarize

  1. Row to column use groupby+sumif,列转行用union all
  2. UNION and UNION ALL efficiency:

Both the UNION and UNION ALL keywords combine two result sets into one, but both are different in terms of usage and efficiency.

  • Handling of duplicate results: UNION will filter out duplicate records after table linking, and Union All will not remove duplicate records.
  • Processing of sorting: Union will sort according to the order of the fields; UNION ALL simply combines the two results and returns.
  • 从效率上说, UNION ALL要比UNION快很多, So, if you can confirm the merged two result sets 不包含重复数据且不需要排序时的话, then use UNION ALL.

• Note: the number of fields in the two SQL statements to be combined must be the same, and the field types must be "compatible" (consistent);

Expansion - table conversion problem

613 The shortest distance on a straight line

insert image description here

select min(abs(p1.x-p2.x)) as shortest
from point p1
join point p2
on p1.x != p2.x
  • After doing the previous question, this question is very simple~

1965 Employee with lost information

select employee_id
from Employees
where employee_id not in (select employee_id from Salaries)
union
select employee_id
from Salaries
where employee_id not in (select employee_id from Employees)
order by employee_id

1264 page recommendations

# Write your MySQL query statement below
select distinct page_id as recommended_page
from Likes
where user_id in (
    (
        select user2_id
        from Friendship
        where user1_id = 1
    )
    union
    (
        select user1_id
        from Friendship
        where user2_id = 1
    )
) and page_id not in (select page_id from Likes where user_id = 1);

Summarize

  • This question needs to pay attention to the usage of not in. If we use !=, when null appears on the right, the statement will be false, so there is no query data. Therefore we should use not in.

608 tree nodes

insert image description here
insert image description here

# Write your MySQL query statement below
select id, (
    case when p_id is null then 'Root'
    when p_id is not null and id in (select p_id from tree) then 'Inner'
    else 'Leaf'
    end
) as Type
from tree

Summarize

  • When not in contains null, the result set is always Empty set
  • For example, the following code is incorrectly written:
select
    id,
    case when p_id is null then "Root"
         when id not in (select p_id from tree) then "Leaf"
         else "Inner"
    end as Type
from
    tree
  • The principle of A not in B is to compare whether the value in table A is equal to the value in table B, that is, a != b. In SQL, null means the absence of an unknown value rather than a null value (see MySQL reference for details).

  • When you judge that any value a != null, the official said, "You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL"any comparison with a null value will return null. Therefore, the return result is no, which can be select if(1 = null, 'true', 'false')confirmed by code.

  • It can be seen from the above principle that when asked, id not in (select p_id from tree)because p_id has a null value, the returned results are all false, so it jumps to the result of else, and the returned value is inner. Therefore, in the answer, the result of leaf is never displayed, and it is all replaced by inner.

534

# 写法1
# Write your MySQL query statement below
select a2.player_id, a2.event_date, sum(a1.games_played) as games_played_so_far
from Activity a1, Activity a2
where a1.player_id = a2.player_id and a2.event_date >= a1.event_date
group by a2.player_id, a2.event_date
order by a2.player_id, a2.event_date


# 写法2
# Write your MySQL query statement below
select player_id, event_date, 
    sum(games_played) over(partition by player_id order by event_date) 
    as games_played_so_far
from Activity

Use of window functions

1783 Number of Grand Slams

# 写法1
# Write your MySQL query statement below
select player_id, player_name, 
    sum(player_id = Wimbledon) + sum(player_id = Fr_open) + 
    sum(player_id = US_open) + sum(player_id = Au_open)
    as grand_slams_count
from Players, Championships
group by player_id, player_name
having grand_slams_count > 0

# 写法2
select player_id, player_name, count(*) as grand_slams_count
from Players join (
    select Wimbledon from Championships 
    union all
    select Fr_open from Championships
    union all
    select US_open from Championships 
    union all
    select Au_open from Championships  
) t
on Players.player_id = t.Wimbledon
group by player_id, player_name;

Summarize

  1. The difference between union all and union: image explanation of union all and union and union
  2. The if judgment condition format used in the sum function is:sum(if(条件,列值,0))
#order_type:订单类型
#open_id:用户唯一标识
SELECT
    date(create_time) AS '当天日期',
    sum(real_price) AS '当天总收入',
sum函数中使用if判断条件:{
sum(
IF (order_type = 0, real_price, 0)
) AS '当天支付收入',
sum(
IF (order_type = 1, real_price, 0)
) AS '当天打赏收入',
}
    count(DISTINCT open_id) AS '付费总人数',
count函数中使用if判断条件:{
count(
DISTINCT open_id,
IF (order_type = 0, TRUE, NULL)
) AS '支付人数',
count(
DISTINCT open_id,
IF (order_type = 1, TRUE, NULL)
) AS '打赏人数',
}
    count(id) AS '付费订单总数',
count函数中使用if判断条件:{
count(
DISTINCT id,
IF (order_type = 0, TRUE, NULL)
) AS '支付订单数',
count(
DISTINCT id,
IF (order_type = 1, TRUE, NULL)
) AS '打赏订单数'
}
FROM
orders
WHERE
'real_price' != 1
AND 'status' != 0
GROUP BY DATE(create_time)

Note: sum is a summation function. When the condition is true, the sum of column values ​​(field names) is executed, that is, accumulation. When the condition is false, it is 0 summation (of course it is still 0)

(1) Single-condition judgment format,sum(if(条件字段名=值,需要计算sum的字段名,0))

(2) Multi-condition judgment format,sum(if(条件字段名>值 AND 条件字段名>值 AND 条件字段名=值,1,0))

Note: The overall meaning of the multi-condition judgment format is to calculate the total number of data that meets the conditions. If the conditions are met, then the total number of data is increased by 1, so the meaning of 1 is to add 1

(3) Common case when format,sum(case when 条件字段名 in (范围较小值,范围较大值) then [需要计算sum的字段名] else 0 end)

  1. The if judgment condition format used in the count function is:

(1) The total number of statistics,count(if(条件字段名=值,true,null))

(2) Statistical totals to de-duplicate values,count(DISTINCT 需要计算count的字段名,if(条件字段名=值,true,null))

1747 Leetflex accounts that should be banned

insert image description here

# Write your MySQL query statement below
select distinct l1.account_id
from LogInfo l1
join LogInfo l2
on l1.account_id = l2.account_id and l1.ip_address != l2.ip_address 
and l2.login between l1.login and l1.logout;

Summarize

Guess you like

Origin blog.csdn.net/weixin_40433003/article/details/130440983