4

在对“链接”表的查询返回的结果中,我还想添加一个额外的列,该列显示从JOIN每行“toTable”值的条件中选择的“DisplayName”值。此外,有时“DisplayName”值是列连接的结果。

我的问题是我该怎么做?

我可以编写单独的查询并结合起来,UNION ALL但我想知道是否有条件的方法来做到这一点

“链接”表中的每个条目都描述了两个表(可能的 3 个或更多表)中的一对条目之间的链接。

链接表:

| LinkID | fromTable | fromID | toTable | toID |
|      1 |        A  |      1 |      B  |    1 |
|      2 |        A  |      1 |      C  |    2 |
|      3 |        B  |      1 |      C  |    1 |
|      4 |        C  |      1 |      A  |    1 |

我想要的查询结果: 例如 WHERE Links.fromTable = 'A' OR Links.fromTable = 'C'

| LinkID | fromTable | fromID | toTable | toID | DisplayName      |
|      1 |        A  |      1 |      B  |    1 |  Some Title      |
|      2 |        A  |      1 |      C  |    2 |  Loud-Quack      |
|      4 |        C  |      1 |      A  |    1 |  Linus           |

3个不同列的表:

Table A:    
| ID  | Name  |
| 1   | Linus |

-

Table B:    
| ID  | Title      |
|  1  | some title |

-

Table C:    
| ID  | CategoryA | CategoryB |
| 1   |   Bark    |    Softly |
| 2   |   Quack   |    Loud   |

- 这就是我这样做的方式UNION ALL,这不是很灵活:编辑:实际上我认为下面是错误的,我现在正在看这个:

SELECT Links.*, A.Name AS DisplayName
FROM Links 
JOIN A ON Links.toID = A.ID 
WHERE Links.fromType IN ('A') AND Links.toType IN ('B')

UNION ALL

SELECT Links.*, CONCAT(C.CategoryB,'-',C.CategoryA) AS DisplayName
FROM Links 
JOIN C ON Links.toID = C.ID 
WHERE Links.fromType IN ('A') AND Links.toType IN ('C')
4

2 回答 2

5

我觉得你需要inline CASE声明

SELECT  a.*,
        CASE toTable
            WHEN 'A' THEN b.Name
            WHEN 'B' THEN c.Title
            WHEN 'C' THEN CONCAT(d.CategoryB , '-',d.CategoryA )
        END AS DisplayName
FROM    `links` a
            LEFT JOIN tableA b
                ON a.toID = b.ID
            LEFT JOIN tableB c
                ON a.toID = c.ID
            LEFT JOIN tableC d
                ON a.toID = d.ID
WHERE   fromtable IN ('A', 'C')

SQLFiddle 演示

于 2012-09-03T00:55:33.327 回答
1

好吧,使用您的示例查询,您可以这样做:

SELECT Links.*, COALESCE(A.Name,CONCAT(C.CategoryB,'-',C.CategoryA)) AS DisplayName
FROM Links 
LEFT OUTER JOIN A ON Links.toID = A.ID 
    AND Links.fromType IN ('A') AND Links.toType IN ('B')
LEFT OUTER JOIN C ON Links.toID = C.ID 
    AND Links.fromType IN ('A') AND Links.toType IN ('C')

只要您始终从连接的表中获得最多一个匹配项(即,您没有两个具有相同和标准的不同连接),此方法就可以工作。Links.fromType IN ...Links.toType IN ...

于 2012-09-03T00:52:36.240 回答