2012-07-03 137 views
0
Table 
Class Firstname Lastname mark 
V  John  Lim   60 
V  Wills  smith  80 
VI  Mark  Bay   75 
VI  Carl  mark  65 

我在我的SQL中有這個表。我需要一個單一的查詢基於從一個表中的「類類型」單個查詢從一個表中檢索兩個xml結果

下面是我的預期結果

Result1 
<Studentslist> 
<Students> 
     <class>V</class> 
     <Firstname>John</Firstname> 
     <Lastname>Lim</Lastname> 
     <mark>60</mark> 
</Students> 
<Students> 
     <class>V</class> 
     <Firstname>Wills</Firstname> 
     <Lastname>smith</Lastname> 
     <mark>80</mark> 
</Students> 
</Studentslist> 

Result2 
<Studentslist> 
<Students> 
     <class>VI</class> 
     <Firstname>Mark</Firstname> 
     <Lastname>Bay</Lastname> 
     <mark>75</mark> 
</Students> 
<Students> 
     <class>VI</class> 
     <Firstname>Carl</Firstname> 
     <Lastname>mark</Lastname> 
     <mark>65</mark> 
</Students> 
<Studentslist> 

千恩萬謝檢索兩個不同的XML結果!

回答

0

查詢部分,使用UNION

(SELECT class, firstname, lastname, mark from students where class='V') 
UNION ALL 
(SELECT class, firstname, lastname, mark from students where class='VI') 

編輯:使用光標

DELIMITER | 
Drop procedure if exists `GetData`; 
CREATE PROCEDURE `GetData`() 


BEGIN 


    DECLARE bDone INT; 
    DECLARE var1 CHAR(16); 

    DECLARE curs CURSOR FOR SELECT distinct(class) FROM students; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1; 

    SET bDone = 0; 

    DROP TEMPORARY TABLE IF EXISTS tblResults; 
    CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
    class varchar(255), 
    firstname varchar(255), 
    lastname varchar(255), 
    mark varchar(255) 
); 

    OPEN curs; 


    emp_loop: LOOP 
    FETCH curs INTO var1; 
    IF bDone=1 THEN  /* No more rows*/ 
       LEAVE emp_loop; 
    END IF; 

    INSERT INTO tblResults SELECT class, firstname, lastname, mark FROM `students` where class=var1; 

    END LOOP emp_loop; 

    CLOSE curs; 
    SELECT * FROM tblResults; 
END| 
DELIMITER ; 
+0

嗨SEL,答覆表示感謝。有沒有其他的方式做這個沒有where子句?這是因爲我不會事先知道類的類型。 – ngweixiong

+0

那麼如何使用光標呢?編輯答案。 – sel

+0

它的工作原理!謝謝! – ngweixiong

相關問題