我第一次使用这个。
SELECT classroom .cls_id,
classroom.cls_name,
u1.users_id as users_id1,
u2.users_id as users_id2
FROM classroom
INNER JOIN clsown
ON clsown.cls_id = classroom .cls_id
INNER JOIN users AS u1
ON clsown.users_id = u1.users_id
INNER JOIN users AS u2
ON clsown.users_id = u2.users_id
我明白了:
cls_id cls_name users_id1 users_id2
1 -------- room1 ------- 1 --------- 1
1 -------- room1 ------- 2 --------- 2
2 -------- room2 ------- 3 --------- 3
2 -------- room2 ------- 4 --------- 4
我想看看
cls_id cls_name users_id1 users_id2
1 -------- room1 ------- 1 --------- 2
2 -------- room2 ------- 3 --------- 4
我不知道如何做内连接。我做错了什么?
感谢回答。
答案 0 :(得分:1)
您在此处注意到的查询实际上需要一个数据透视表,因为您希望获取cls_id和cls_name的唯一值,然后将用户命名为列。
我在2009年写了this article,说明如何做这样的事情。它应该有帮助
答案 1 :(得分:0)
我假设您使用Mysql
作为RDBMS
,如果是,您可以使用GROUP_CONCAT()根据need显示records
,但是以不同的形式。即,此查询会将您想要的所有其他coloumns
填充到由cell
分隔的单个separator
中。
SELECT classroom .cls_id,
classroom.cls_name,
GROUP_CONCAT(u1.users_id ORDER BY u1.users_id SEPARATOR ', ') Users
FROM classroom
INNER JOIN clsown
ON clsown.cls_id = classroom .cls_id
INNER JOIN users AS u1
ON clsown.users_id = u1.users_id
Group by classroom .cls_id
上述查询将返回如下记录,
cls_id cls_name users
1 room1 1,2
2 room2 3,4
答案 2 :(得分:0)
由于您使用的是SQL Server,因此有几种方法可以转移数据。
您可以使用带有CASE
表达式的聚合函数:
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;
或者您可以使用PIVOT
功能:
select cls_id,
cls_name,
user_id1,
user_id2
from
(
SELECT cr .cls_id,
cr.cls_name,
u1.users_id,
'user_id'+cast(ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) as varchar2)) col
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
pivot
(
max(users_id)
for col in (user_id1, user_id2)
) piv;