select inner join column2 NULL [closed]

我只是一个虾纸丫 提交于 2019-12-11 20:11:58

问题


table clsown

id cls_id users_id

1----1---------1

2----1---------2

sql

select cls_id,
cls_name,
MAX(case when rn = 1 then users_id end) user_id1,
MAX(case when rn = 2 then users_id end) user_id2
from
(
SELECT cr.cls_id, 
    cr.cls_name, 
    u1.users_id,
    ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
FROM classroom cr
INNER JOIN clsown co
    ON co.cls_id = cr.cls_id 
INNER JOIN users AS u1 
    ON co.users_id = u1.users_id and u1.users_id =1
) d
group by cls_id, cls_name;

i get this

cls_id cls_name users_id1 users_id2
  1     room1       1        NULL

i want see

cls_id cls_name users_id1 users_id2
  1     room1       1         2

回答1:


Your code has a and u1.users_id =1 in it, which is why you're getting the results you're seeing. bluefeet's SQL Fiddle shows the results without that and it looks like it works fine.

select cls_id,
    cls_name,
    MAX(case when rn = 1 then users_id end) user_id1,
    MAX(case when rn = 2 then users_id end) user_id2
from
(
    SELECT cr.cls_id, 
        cr.cls_name, 
        u1.users_id,
        ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
    FROM classroom cr
    INNER JOIN clsown co
        ON co.cls_id = cr.cls_id 
    INNER JOIN users AS u1 
        ON co.users_id = u1.users_id 
) d
group by cls_id, cls_name;

SQL Fiddle Demo




回答2:


Remove the and ul.users_id = 1 from the on clause:

select cls_id,
cls_name,
MAX(case when rn = 1 then users_id end) user_id1,
MAX(case when rn = 2 then users_id end) user_id2
from
(
SELECT cr.cls_id, 
    cr.cls_name, 
    u1.users_id,
    ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
FROM classroom cr
INNER JOIN clsown co
    ON co.cls_id = cr.cls_id 
INNER JOIN users AS u1 
    ON co.users_id = u1.users_id
) d
group by cls_id, cls_name;


来源:https://stackoverflow.com/questions/15664926/select-inner-join-column2-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!