【发布时间】:2020-03-04 20:45:42
【问题描述】:
我有 2 张桌子、书籍和流派订单。我正在尝试从书籍(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?另外,如何避免冗余列?
【问题讨论】:
-
你能添加一个模式(你想要什么)吗?
-
'另外,如何避免冗余列?'指定列名而不是 *。 '是否可以更改结果集中的 book_id' - 是的,但我不清楚你想要 1,2,3,4,5 还是 1,2,1,2,1
-
@Tushar 我编辑显示预期结果
-
@P.Salmon 我没想到,谢谢。
-
@JonZee 我添加了一个答案,希望第二个查询能够成功。