2017-11-08 13 views
1

私は2つのテーブルを持っています。私は1番目のテーブルの中で2番目のテーブルの価値が最低限必要です。私は列least_t2を記入したいと思っています。値はtable2から最低値になります。ケース時最小値は他のテーブル

table1 
id name d1 d2 d3 
1 asd 1 2 3 
table2 
id name c1 c2 c3 c4 
1 poi 7 5 6 9 

マイ出力テーブルマイクエリが通りであるtable1

id name d1 d2 d3 least least_t2 
1 asd 1 2 3 1  b 

から以下のようにウィル:Noの結果が表示されていない上記のクエリで

select * , least(d1, d2, d3), 
    (CASE least(d1, d2, d3) 
     WHEN d1 THEN (CASE least(c1, c2, c3, c4) from `table2` 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END) 
     WHEN d2 THEN (CASE least(c1, c2, c3, c4) from `table2` 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END) 
     WHEN d3 THEN (CASE least(c1, c2, c3, c4) from `table2` 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END) 

END) as least_t2 
FROM `table1` 

答えて

1

は、この文字列で検索してください:

SELECT 
    t1.*, 
    LEAST(t1.d1, t1.d2, t1.d3) AS `least`, 
    CASE WHEN t2.c1 = LEAST(t2.c1, t2.c2, t2.c3, t2.cr) THEN 'a' 
     WHEN t2.c2 = LEAST(t2.c1, t2.c2, t2.c3, t2.cr) THEN 'b' 
     WHEN t2.c3 = LEAST(t2.c1, t2.c2, t2.c3, t2.cr) THEN 'c' 
     WHEN t2.c4 = LEAST(t2.c1, t2.c2, t2.c3, t2.cr) THEN 'd' 
     ELSE 'Unknown' END AS least_t2 
FROM table1 t1 
LEFT JOIN table2 t2 
    ON t1.id = t2.id 
1

idを使用してtable1table2を結合できる場合、次のクエリが実行されます。

select t1.*, 
     least(d1, d2, d3) as least, 
     case least(c1, c2, c3, c4) 
      when c1 then 'a' 
      when c2 then 'b' 
      when c3 then 'c' 
      when c1 then 'd' 
     end as least_t2 
from table1 t1 
inner join table2 t2 
on t1.id=t2.id 
1

次のコードを確認してください。

select * , least(d1, d2, d3), 
    (CASE least(d1, d2, d3) 
     WHEN d1 THEN (select CASE least(c1, c2, c3, c4) 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END from `table2`) 
     WHEN d2 THEN (select CASE least(c1, c2, c3, c4) 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END from `table2`) 
     WHEN d3 THEN (select CASE least(c1, c2, c3, c4) 
           WHEN c1 THEN 'a' 
           WHEN c2 THEN 'b' 
           WHEN c3 THEN 'c' 
           WHEN c4 THEN 'd' 
         END from `table2`) 

END) as least_t2 
FROM `table1` 

または

select * , least(d1, d2, d3),(select CASE least(c1, c2, c3, c4) WHEN c1 THEN 'a' WHEN c2 THEN 'b' WHEN c3 THEN 'c' WHEN c4 THEN 'd' END from `table2`) as least_t2 
FROM `table1` 
関連する問題