为了账号安全,请及时绑定邮箱和手机立即绑定

多表查询它的排序逻辑到底是怎样的

我这一课的代码如下:

问题出现在第二步,c表的排序跟pm_stu表的排序都是正确的,做两个表的查询之后排序就乱了,加上order by也没用,

笛卡尔积不是从上到下排的吗,搞不懂。

SQL> select ci_id,wm_concat(stu_name) stu_names

  2      from (select c.ci_id,d.stu_name

  3                from (select a.ci_id,b.stu_id

  4                          from pm_ci a,pm_stu b

  5                          where instr(a.stu_ids,b.stu_id)>0) c,

  6                  pm_stu d

  7                  where c.stu_id=d.stu_id) e

  8         group by ci_id;


CI_ID                STU_NAMES

-------------------- --------------------------------------------------------------------------------

1                    张三,赵六,王五,李四

2                    张三,赵六


实现逻辑:

1、通过instr函数获取ci_id,stu_id的一个表

SQL> (select a.ci_id,b.stu_id

  2        from pm_ci a,pm_stu b

  3        where instr(a.stu_ids,b.stu_id)>0)

  4  ;


CI_ID                STU_ID

-------------------- --------------------

1                    1

1                    2

1                    3

1                    4

2                    1

2                    4


6 rows selected

2、用c表跟pm_stu关联查询,得到ci_id,stu_name的表

SQL> select * from pm_stu

  2  ;


STU_ID               STU_NAME

-------------------- --------------------

1                    张三

2                    李四

3                    王五

4                    赵六


SQL> 

SQL> select c.ci_id,d.stu_name

  2  from (select a.ci_id,b.stu_id

  3        from pm_ci a,pm_stu b

  4        where instr(a.stu_ids,b.stu_id)>0) c,

  5        pm_stu d

  6  where c.stu_id=d.stu_id

  7  ;


CI_ID                STU_NAME

-------------------- --------------------

2                    张三

1                    张三

1                    李四

1                    王五

2                    赵六

1                    赵六


6 rows selected

3、最后行转列

SQL> select ci_id,wm_concat(stu_name) stu_names

  2  from (select c.ci_id,d.stu_name

  3        from (select a.ci_id,b.stu_id

  4              from pm_ci a,pm_stu b

  5              where instr(a.stu_ids,b.stu_id)>0) c,

  6              pm_stu d

  7        where c.stu_id=d.stu_id) e

  8  group by ci_id;


CI_ID                STU_NAMES

-------------------- --------------------------------------------------------------------------------

1                    张三,赵六,王五,李四

2                    张三,赵六


正在回答

举报

0/150
提交
取消

多表查询它的排序逻辑到底是怎样的

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信