多表查詢(xún)它的排序邏輯到底是怎樣的
我這一課的代碼如下:
問(wèn)題出現(xiàn)在第二步,c表的排序跟pm_stu表的排序都是正確的,做兩個(gè)表的查詢(xún)之后排序就亂了,加上order by也沒(méi)用,
笛卡爾積不是從上到下排的嗎,搞不懂。
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? ? ? ? ? ? ? ? ? ? 張三,趙六
實(shí)現(xiàn)邏輯:
1、通過(guò)instr函數(shù)獲取ci_id,stu_id的一個(gè)表
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關(guān)聯(lián)查詢(xún),得到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、最后行轉(zhuǎn)列
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? ? ? ? ? ? ? ? ? ? 張三,趙六