1

我有 3 张桌子。

tb_employees:

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

tb_要求:

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

tb_详细信息:

+---------------+-----------------+---------------+
|  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      |
+---------------+-----------------+---------------+

我要做的是SELECTrequirem描述)和特定员工(例如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。

我真的不知道该怎么做。

你能帮帮我吗?

谢谢你的回答。

4

1 回答 1

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

| 要求 | VIRTUAL_COLUMN |
|-----------------|----------------|
| 照片 | 0 |
| 犯罪记录 | 1 |
| 射击测试 | 1 |

输出id_employee = 3

| 要求 | VIRTUAL_COLUMN |
|-----------------|----------------|
| 照片 | 1 |
| 犯罪记录 | 0 |
| 射击测试 | 1 |

这是SQLFiddle演示

进一步阅读:

于 2013-11-06T17:40:41.443 回答