用带有MAX(ID)的native nativeQuery弥补以获得2个对象

时间:2018-09-13 03:14:38

标签: mysql hibernate spring-data-jpa

我有一个名为Story的表

sID |  sName  |  sView  
 1  |   s1    |    1  
 2  |   s2    |    11  
 3  |   s3    |    142 
 4  |   s4    |    152

表格章节:

 chID  |  sID  |  chName  |  chContent
   1   |   1   |    ch1   |    aaa  
   2   |   2   |    ch2   |    aaa  
   3   |   3   |    ch3   |    aaa  
   4   |   1   |    ch4   |    aaa  
   5   |   3   |    ch5   |    aaa  
   6   |   1   |    ch6   |    aaa  
   7   |   2   |    ch7   |    aaa  

NaviteQuery:

SELECT s.*, MAX(c.chID) as chapterID FROM Story s 
       LEFT JOIN Chapter c ON s.sID = c.sID
       GROUP BY s.sID

结果:

 sID |  sName  |  sView  |  chapterID  
  1  |   s1    |    1    |      6
  2  |   s2    |    11   |      7
  3  |   s3    |    142  |      5
  4  |   s4    |    152  |     null

但是您应该得到一个'SELECT s'。 *, C。 * FROM ....',谁可以帮助我!!!!

1 个答案:

答案 0 :(得分:0)

您可以用一些不同的方式编写它。例如,您可以使用它:

SELECT s.*, c.* FROM Story s 
       LEFT JOIN (SELECT * FROM Chapter c INNER JOIN (SELECT MAX(c.chID) as chapterID FROM Story s 
       LEFT JOIN Chapter c ON s.sID = c.sID
       GROUP BY s.sID) d ON c.chID = d.chapterID) c ON s.sID = c.sID