MySQL - 使用标题名称作为查询过滤器的一部分

时间:2013-04-10 23:36:40

标签: mysql

我对MySQL比较陌生,遇到了一个我似乎无法找到解决方案的问题。我搜索过但找不到答案。我很开放我可能没有正确地提出这个问题。这是:

我正在尝试使用给定列的名称以及来自一个表的该列中的值来从另一个表中提取值。第一个表包含3列,其中包含响应编码。第二个表包含每个项目的每个代码的定义。相同的数字代码根据项目与不同的含义相关联。例如:

table1 (this table cannot change):
--------------------------------------------------------------
|result_id | f_initial | l_name   | item_A | item_B | item_C |
--------------------------------------------------------------
|    1     |     j     |   doe    |   1    |   3    |   2    |
|    2     |     k     |  smith   |   3    |   1    |   2    |
|    3     |     l     | williams |   2    |   2    |   1    |
--------------------------------------------------------------


table2 (this table can be modified, split, or whatever needs to be done):
-------------------------------------------
|item_id | item_name | score | definition |
-------------------------------------------
|   1    |  item_A   |   1   |   agree    |
|   2    |  item_A   |   2   |  neutral   |
|   3    |  item_A   |   3   |  disagree  |
|   4    |  item_B   |   1   |   likely   |
|   5    |  item_B   |   2   | not likely |
|   6    |  item_B   |   3   |  no reply  |
|   7    |  item_C   |   1   |     yes    |
|   8    |  item_C   |   2   |     no     |
-------------------------------------------

My goal is for the query to output the following:
--------------------------------------------------------------------
|result_id | f_initial |  l_name  |  item_A  |  item_B    | item_C |
--------------------------------------------------------------------
|    1     |     j     |    doe   |   agree  |  no reply  |   no   |
|    2     |     k     |   smith  | disagree |   likely   |   no   |
|    3     |     l     | williams |  neutral | not likely |   yes  |
--------------------------------------------------------------------

非常感谢任何帮助或指导。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您必须加入item_A/B/Cscore

上的两个表格
select t1.result_id, t1.f_initial, t1.l_name,
       t2a.definition as item_a,
       t2b.definition as item_b,
       t2c.definition as item_c
from table1 t1
join table2 t2a on t2a.score = t1.item_a
join table2 t2b on t2b.score = t1.item_b
join table2 t2c on t2c.score = t1.item_c
where t2a.item_name = 'item_A'
      and t2b.item_name = 'item_B'
      and t2c.item_name = 'item_C'