更改mysql join结果集中的ID值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更改mysql join结果集中的ID值相关的知识,希望对你有一定的参考价值。

我有2张桌子,书籍和genre_order。我试图从books(t1)中选择所有值,并使用JOIN从genre_order(t2)中的order列按流派对它们进行排序。结果集对它们的排序很好,但是,我对如何更改book_id以反映新的顺序感到困惑。

table : books
+-------+------------------+-----------+
|book_id|   name           |   genre   |
+-------+------------------+-----------+
|   1   |   Harry Potter   |  Fantasy  |
|   2   |   The Alchemist  |  Fantasy  |
|   3   |   Inferno        |  Thriller |
|   4   |   Steve Jobs     |  Biography|
|   5   |   John Adams     |  Biography|
+-------+------------------+-----------+


table : genre_order
+-----------+-------+
|   genre   | order |
+-----------+-------+
| Biography |  1    |
| Fantasy   |  2    |
| Thriller  |  3    |
+-----------+-------+ 

查询:

SELECT * FROM books t1 JOIN genre_order t2 ON t1.genre = t2.genre ORDER BY t2.order ASC 

结果:

  +-------+------------------+-----------+-----------+------+
  |book_id|   name           |   genre   |  genre    | order|
  +-------+------------------+-----------+-----------+------+
  |   4   |   Steve Jobs     |  Biography|  Biography|  1   |
  |   5   |   John Adams     |  Biography|  Biography|  1   |
  |   1   |   Harry Potter   |  Fantasy  |  Fantasy  |  2   |
  |   2   |   The Alchemist  |  Fantasy  |  Fantasy  |  2   |
  |   3   |   Inferno        |  Thriller |  Thriller |  3   |
  +-------+------------------+-----------+-----------+------+

预期结果:

  +-------+------------------+-----------+------+
  |book_id|   name           |   genre   | order|
  +-------+------------------+-----------+------+
  |   1   |   Steve Jobs     |  Biography|  1   |
  |   2   |   John Adams     |  Biography|  1   |
  |   3   |   Harry Potter   |  Fantasy  |  2   |
  |   4   |   The Alchemist  |  Fantasy  |  2   |
  |   5   |   Inferno        |  Thriller |  3   |
  +-------+------------------+-----------+------+

是否可以在结果集中更改book_id?另外,如何避免多余的列?

答案

尝试此代码

SELECT ROW_NUMBER() over (order by pk_field ) as book_id,t1.name,t2.genre,t2.order FROM books t1 JOIN genre_order t2 ON t1.genre = t2.genre ORDER BY t2.order ASC 

以上是关于更改mysql join结果集中的ID值的主要内容,如果未能解决你的问题,请参考以下文章

java - 如何在Java中从MySQL结果集中的while循环中添加值?

sql left join - 如果没有结果,则返回默认值

MYSQL - 将 SUM 与 JOIN 结合使用

使用 INNER JOIN 排除 MYSQL 查询结果

MySQL JOIN 的结果 UNION

将 MySQL join 返回的结果限制为 1