从SQL表中选择并加入(选择语句+ Hibernate代码)

时间:2017-11-16 16:24:15

标签: java mysql sql hibernate join

我有以下两个表:

“学生”和“技能”表

STUDENT table
"id"         "name"
1             Peter
2              David
3             Mark

SKILL table
"id"    "id_student"    "skill"     "skill value"
1            1            height              180
2            1            weight              75
3            2            height              170
4            3            height              180

我想选择“每个学生身高180,身高75,”彼得“的名字。”

我需要的主要内容是SQL语句,但如果有人可以告诉我如何使用Java + Hibernate(我的意思是如何创建Criteria对象),这将非常有用。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

如果没有提供整个游戏,这会有帮助吗?

DROP TABLE IF EXISTS student;

CREATE TABLE student
(id INT NOT NULL aUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
);

INSERT INTO student VALUES
(1,'Peter'),
(2,'David'),
(3,'Mark'),
(4,'Peter'),
(5,'Brian');


DROP TABLE IF EXISTS student_skill;

CREATE TABLE student_skill
(id_student INT NOT NULL
,skill VARCHAR(20) NOT NULL
,value INT NOT NULL 
,PRIMARY KEY(id_student,skill)
);

INSERT INTO student_skill VALUES
(1,'height',180),
(1,'weight',75),
(2,'height',170),
(3,'height',180),
(4,'height',170),
(4,'weight',75),
(5,'height',180),
(5,'weight',75);

查询1。

SELECT x.*
     , y.height
     , y.weight 
  FROM student x 
  JOIN 
     ( SELECT id_student
            , MAX(CASE WHEN skill = 'height' THEN value END) height
            , MAX(CASE WHEN skill = 'weight' THEN value END) weight 
         FROM student_skill 
        GROUP 
           BY id_student
     ) y
    ON y.id_student = x.id;
+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+

...或者,查询2。

SELECT s.*
     , h.value height
     , w.value weight
  FROM student s
  LEFT 
  JOIN student_skill h
    ON h.id_student = s.id
   AND h.skill = 'height'
  LEFT
  JOIN student_skill w
    ON w.id_student = s.id
   AND w.skill = 'weight';

+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+