从多列连接到一个表

时间:2012-07-30 06:16:35

标签: mysql sql join

我有一个表格genrelink和其他属性描述,其中有以下列

Genere link table :

titleID
GENID1
GENID2
GENID3
GENID4
GENID5

GenereDesscription table

GENID
DESC

我希望在一次点击中获得Genere Link的所有GENID的Genere desciption ...查询

3 个答案:

答案 0 :(得分:1)

这应该适合你:

SELECT titleID,
    b.description AS description1,
    c.description AS description2,
    d.description AS description3,
    e.description AS description4,
    f.description AS description5
FROM Genere a
    LEFT JOIN GenereDesscription b
        ON a.GENID1 = b.GENID
    LEFT JOIN GenereDesscription c
        ON a.GENID2 = c.GENID
    LEFT JOIN GenereDesscription d
        ON a.GENID3 = d.GENID
    LEFT JOIN GenereDesscription e
        ON a.GENID4 = e.GENID
    LEFT JOIN GenereDesscription f
        ON a.GENID5 = f.GENID;

答案 1 :(得分:0)

使用多个联接,为每个ID加入一次。

SELECT ...
FROM `Genere link` l
INNER JOIN GenereDesscription d1 ON l.GENID1 = d1.GENID
INNER JOIN GenereDesscription d2 ON l.GENID2 = d2.GENID
INNER JOIN GenereDesscription d3 ON l.GENID3 = d3.GENID
INNER JOIN GenereDesscription d4 ON l.GENID4 = d4.GENID
INNER JOIN GenereDesscription d5 ON l.GENID5 = d5.GENID

答案 2 :(得分:0)

SELECT 
  titleID,
  gdesc1.DESC,
  gdesc2.DESC,
  gdesc3.DESC,
  gdesc4.DESC,
  gdesc5.DESC
FROM 
  genrelink
JOIN 
  GenereDesscription AS gdesc1 ON genrelink.GENID1 = gdesc1.GENID
JOIN 
  GenereDesscription AS gdesc2 ON genrelink.GENID1 = gdesc2.GENID
JOIN 
  GenereDesscription AS gdesc3 ON genrelink.GENID1 = gdesc3.GENID
JOIN 
  GenereDesscription AS gdesc4 ON genrelink.GENID1 = gdesc4.GENID
JOIN 
  GenereDesscription AS gdesc5 ON genrelink.GENID1 = gdesc5.GENID

但应该建议您的架构将受益于规范化。这是多对多的,应该这样建模:

Titles
id

Genres
id
description

titleGenres
titleID
genreID