2013-04-10 77 views
0

我對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 | 
-------------------------------------------------------------------- 

任何幫助或指導,非常感謝。先謝謝你。

回答

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

這完美地工作的兩個表。非常感謝。 – 2013-04-11 14:51:23