1

我第一次用这个。

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

我不知道如何进行内部连接。我究竟做错了什么?

感谢您的回答。

4

3 回答 3

1

您在此处记录的查询实际上需要一个数据透视表,因为您希望获取 cls_id 和 cls_name 的唯一值,然后将用户排序到列中。

我在 2009 年写了这篇文章,展示了如何做这样的事情。它应该有帮助

于 2013-03-26T16:23:42.393 回答
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;
于 2013-03-26T18:08:23.120 回答
0

我假设您使用Mysql的是您的RDBMS,如果是这样,您可以使用GROUP_CONCAT()records根据您的需要显示,但以不同的形式。ie] 此查询会将coloumns您想要的所有其他内容填充到一个cellseparator.

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 

编辑: 在 Sql server 中实现上述结果的参考

于 2013-03-26T17:50:36.213 回答