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>

非常感谢!

4

1 回答 1

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 ;
于 2012-07-03T04:20:54.283 回答