MySQL之SQL語句實現將三個查詢結果集拼接成一個表

來源:互聯網
上載者:User

標籤:

遇到的問題:

現在利用SQL語句查詢得到三個結果集,每一個結果集是兩列,具體為排名序號與對應的名字,如下表一。但是現在需要將這三個結果集拼接成為一個表,並且只有一個排名序號。

排名 姓名
1 張三
2 李四

 

 

 

利用SQL語句實現:


SELECT rownum, MAX(post1) AS post1,MAX(post2) AS post2,MAX(post3) AS post3
FROM
(SELECT @rownum1 := @rownum1 + 1 AS rownum, firstname AS post1,‘‘ AS post2,‘‘ AS post3
FROM
(SELECT firstname
FROM
exam_main a,
exam_rel_user b,
account c,
core_dept d
WHERE a.`id` = b.`exam_id`
AND b.`user_id` = c.`user_id`
AND c.`dept_id` = d.`id`
AND c.`position` IN (
‘01010101‘,
‘01010102‘,
‘01010104‘
)
ORDER BY b.score DESC,
b.last_attempt_date ASC) aa,
(SELECT
@rownum1 := 0) bb

UNION ALL

SELECT @rownum2 := @rownum2 + 1 AS rownum, ‘‘ AS post1,firstname AS post2, ‘‘ AS post3
FROM
(SELECT
firstname
FROM
exam_main a,
exam_rel_user b,
account c,
core_dept d
WHERE a.`id` = b.`exam_id`
AND b.`user_id` = c.`user_id`
AND c.`dept_id` = d.`id`
AND c.`position` IN (
‘01010201‘,
‘01010202‘,
‘01010204‘
)
ORDER BY b.`score` DESC,
b.`last_attempt_date` ASC) aa,
(SELECT
@rownum2 := 0) bb

union all

SELECT @rownum3 := @rownum3 + 1 AS rownum,‘‘ as post1, ‘‘ as post2, firstname as post3  //這裡的兩個單引號分別代表兩個空值,也就是把post1與post2值設為空白,最後也就是把第一列與第二列的設為空白的一列。
from
(SELECT
firstname
FROM
exam_main a,
exam_rel_user b,
account c,
core_dept d
WHERE a.`id` = b.`exam_id`
AND b.`user_id` = c.`user_id`
AND c.`dept_id` = d.`id`
AND c.`position` IN (‘01010203‘, ‘01010206‘)
ORDER BY b.`score` DESC,
b.`last_attempt_date` ASC) aa,
(SELECT
@rownum3 := 0) bb

) cc

/* where rownum = 1*/
group by rownum

註:

1.這裡面涉及四個表exam_main a,  exam_rel_user b,  account c,  core_dept d ,其中考試記錄表exam_main中的id為考試結果表exam_rel_user的exam_id外鍵,考試結果表中user_id外鍵為人員表中user_id,人員表中dept_id外鍵為core_dept部門表中的id。

2.每個結果集看作是一個表,三個結果集用 union all 串連,最後將三個結果集又看做一個表。

3.用SQL語句產生排名序號利用的是在結果集(當做一個表)之外添加查詢.如下:

 SELECT @rownum := @rownum + 1 AS rownum,‘‘ as post1, ‘‘ as post2, firstname as post3
 FROM   (結果集)aa

(SELECT @rownum3 := 0) bb 

此處勿忘在最後的括弧外添加別名,否則會出錯。

 

MySQL之SQL語句實現將三個查詢結果集拼接成一個表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.