1

在数据库中有 2 个表,用于包含类型的书籍

--------------------
| id | genre       |
--------------------
| 1  |   genre 1   |
| 2  |   genre 2   |
| 3  |   genre 3   |
| 4  |   genre 2   |
--------------------

和表格书籍,每本书的类别有 4 列

---------------------------------
| id | name | c1 | c2 | c3 | c4 |
---------------------------------
|7427| book1| 3  | 1  | 0  | 0  |

如何通过 ID 获取图书的所有类别?

我尝试了 2 种类型的人,但第二类的结果和拳头一样

SELECT 
    books.id as bid,
    c1, 
    genre.name as g1_name,
    c2,
    genre.name as g2_name
FROM books 
    Left join genre on books.c1 = genre.id 
where books.id="7427"
;
4

2 回答 2

1

一种方法:

select b.id,
       b.name,
       b.c1,
       g1.genre genre1,
       b.c2,
       g2.genre genre2,
       b.c3,
       g3.genre genre3,
       b.c4,
       g4.genre genre4
from books b
left join genre g1 on b.c1 = g1.id 
left join genre g2 on b.c2 = g2.id 
left join genre g3 on b.c3 = g3.id 
left join genre g4 on b.c4 = g4.id 
where b.id='7427'

SQLFiddle在这里

或者:

select b.id,
       b.name,
       b.c1,
       max(case g.id when c1 then g.genre end) genre1,
       b.c2,
       max(case g.id when c2 then g.genre end) genre2,
       b.c3,
       max(case g.id when c3 then g.genre end) genre3,
       b.c4,
       max(case g.id when c4 then g.genre end) genre4
from books b
left join genre g on g.id in (b.c1, b.c2, b.c3, b.c4)
where b.id='7427'
group by b.id

SQLFiddle在这里

于 2013-07-27T10:14:37.283 回答
0

因此,在您的情况下,仅运行子查询可能更直接:

SELECT 
    books.id as bid,
    c1,
    (SELECT name FROM genre WHERE id = c1) as c1_genre,
    c2,
    (SELECT name FROM genre WHERE id = c2) as c2_genre,
    c3,
    (SELECT name FROM genre WHERE id = c3) as c3_genre,
    c4,
    (SELECT name FROM genre WHERE id = c4) as c4_genre
FROM books 
where books.id="7427";

此外,向组成的表添加一个索引genreid, name这样它就不必为这些查询读取数据页。

于 2013-07-27T10:11:26.023 回答