Sql根据列值选择查询

时间:2014-09-09 10:41:04

标签: sql select join

我有Table1这样:

ApplicableTo IdApplicable
---------------------------
Dept              1
Grade             3
section           1
Designation       2

还有其他表格:

tblDept

ID     Name
1       dept1
2       baking
3       other

tblGrade

ID      Name
1       Grd1
2       Manager
3       gr3

tblSection

id      Name
1       Sec1
2       sec2
3       sec3

tblDesignation

id      Name
1       Executive
2       Developer
3       desig3

我需要的是table1的查询,以这种方式给我

ApplicableTo (table1)
Name (from the relevant table based on the value in `ApplicableTo` column)

这可能吗?

期望的结果:

eg: ApplicableTo IdApplicable Name
      Dept            1       dept1
      grade           3       gr3
      Section         1       sec1
      Designation     2       Developer.

这是我想要的结果。

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作,以便适用于成为JOIN谓词的一部分:

SELECT  t1.ApplicableTo, t1.IdApplicable, n.Name
FROM    Table1 AS t1
        INNER JOIN
        (   SELECT  ID, Name, 'Dept' AS ApplicableTo
            FROM    tblDept
            UNION ALL
            SELECT  ID, Name, 'Grade' AS ApplicableTo
            FROM    tblGrade
            UNION ALL
            SELECT  ID, Name, 'section' AS ApplicableTo
            FROM    tblSection
            UNION ALL
            SELECT  ID, Name, 'Designation' AS ApplicableTo
            FROM    tblDesignation
        ) AS n
            ON n.ID = t1.IdApplicable 
            AND n.ApplicableTo = t1.ApplicableTo

我通常会建议不要使用这种方法,虽然看起来似乎是一种更简洁的方法,但最好还是在表格中有4个单独的可空列:

ApplicableTo | IdDept | IdGrade | IdSection | IdDesignation
-------------+--------+---------+-----------+---------------
Dept         |    1   |  NULL   |    NULL   |     NULL
Grade        |  NULL  |    3    |    NULL   |     NULL
section      |  NULL  |   NULL  |      1    |     NULL
Designation  |  NULL  |   NULL  |    NULL   |       2

这允许您使用外键来正确管理参照完整性。

答案 1 :(得分:0)

实现这一目标的最简单方法是在table1中添加一个额外的列,以保持id被refferred到的表。否则,您无法知道在哪个表中引用了适用的ID。

或者您可以通过以下方式创建适用的id:您可以从中提取表格,例如a1表示tblDept中的id 1。然后使用[case](http://dev.mysql.com/doc/refman/5.0/en/case.html)(对于mysql)来进行正确的Join。

答案 2 :(得分:0)

您可以在此处使用CASE,

SELECT ApplicableTo,
       IdApplicable,
       CASE 
         WHEN ApplicableTo = 'Dept' THEN (SELECT Name FROM tblDept WHERE tblDept.ID = IdApplicable) 
         WHEN ApplicableTo = 'Grade' THEN (SELECT Name FROM tblGrade WHERE tblGrade.ID = IdApplicable)
         WHEN ApplicableTo = 'Section' THEN (SELECT Name FROM tblSection WHERE tblSection.ID = IdApplicable)
         WHEN ApplicableTo = 'Designation' THEN (SELECT Name FROM tblDesignation WHERE tblDesignation.ID = IdApplicable)
       END AS 'Name'
FROM Table1