MySQL - 选择包含值的列并创建“虚拟列”

时间:2013-11-06 17:35:18

标签: mysql select join

我有3张桌子。

tb_employees:

+---------------+---------------+
|  id_employee  |   employee    |
+---------------+---------------+
|     1         | Robert Tomson |
|     2         | Jhonatan Weg  |
|     3         |   Eva Uhte    |
+---------------+---------------+

tb_requirements:

+---------------+-----------------+
|  id_requirem  |    requirem     |
+---------------+-----------------+
|     11        |      Photo      |
|     12        | Criminal Record |
|     13        |  Shooting Test  |
+---------------+-----------------+

tb_details:

+---------------+-----------------+---------------+
|  id_details   |  id_employee    |  id_requirem  |
+---------------+-----------------+---------------+
|     21        |       1         |       11      |
|     22        |       1         |       12      |
|     23        |       1         |       13      |
|     24        |       2         |       12      |
|     25        |       2         |       13      |
|     26        |       3         |       11      |
|     27        |       3         |       13      |
+---------------+-----------------+---------------+

我要做的是SELECT requirem(说明)和特定员工(例如WHERE id_employee = '2')并添加“虚拟列”,以显示员工有这个要求。

喜欢这样:WHERE id_employee = '2'

+----------------+-----------------+
|    requirem    | virtual_column  |
+----------------+-----------------+
|     Photo      |       0         |
|Criminal Record |       1         |
| Shooting Test  |       1         |
+---------------+------------------+

WHERE id_employee = '3'

+----------------+-----------------+
|    requirem    | virtual_column  |
+----------------+-----------------+
|     Photo      |       1         |
|Criminal Record |       0         |
| Shooting Test  |       1         |
+---------------+------------------+

其中0 =员工没有该要求,1 =员工有此要求:来自tb_detail。

我真的不知道该怎么做。

你可以帮帮我吗?

感谢您的回答。

1 个答案:

答案 0 :(得分:3)

实现目标的关键是OUTER JOIN

SELECT r.requirem, (d.id_requirem IS NOT NULL) virtual_column
  FROM tb_requirements r LEFT JOIN tb_details d
    ON r.id_requirem = d.id_requirem
   AND d.id_employee = 2

id_employee = 2的输出:

|        REQUIREM | VIRTUAL_COLUMN |
|-----------------|----------------|
|           Photo |              0 |
| Criminal Record |              1 |
|   Shooting Test |              1 |

id_employee = 3的输出:

|        REQUIREM | VIRTUAL_COLUMN |
|-----------------|----------------|
|           Photo |              1 |
| Criminal Record |              0 |
|   Shooting Test |              1 |

这是 SQLFiddle 演示

进一步阅读: