最初にUNION ALL
を使用してテーブルを正規化します。つまり、すべての行を3つに分割する必要があります。各グループに1つ(INT_1 VALUE1
,INT_2 VALUE2
,INT_3 VALUE3
)。明示的な主キーがないので、すべての列を含めてソース行を識別する必要があります。
select t.*, 1 as position, INT_1 as i, VALUE1 as v from my_table t
union all
select t.*, 2 as position, INT_2 as i, VALUE2 as v from my_table t
union all
select t.*, 3 as position, INT_3 as i, VALUE3 as v from my_table t
結果:
| INT_1 | INT_2 | INT_3 | VALUE1 | VALUE2 | VALUE3 | position | i | v |
|-------|-------|-------|--------|--------|---------|----------|----|---------|
| 33 | 25 | 10 | nice | hello | goodbye | 1 | 33 | nice |
| 10 | 15 | 28 | dice | hay | bird | 1 | 10 | dice |
| 33 | 25 | 10 | nice | hello | goodbye | 2 | 25 | hello |
| 10 | 15 | 28 | dice | hay | bird | 2 | 15 | hay |
| 33 | 25 | 10 | nice | hello | goodbye | 3 | 10 | goodbye |
| 10 | 15 | 28 | dice | hay | bird | 3 | 28 | bird |
http://sqlfiddle.com/#!9/9086d5/1
今サブクエリに入れてWHERE v LIKE '%ice%'
を使用してv
欄にご文字列を検索します。
select *
from (
select t.*, 1 as position, INT_1 as i, VALUE1 as v from my_table t
union all
select t.*, 2 as position, INT_2 as i, VALUE2 as v from my_table t
union all
select t.*, 3 as position, INT_3 as i, VALUE3 as v from my_table t
) n
where v like '%ice%'
結果:
| INT_1 | INT_2 | INT_3 | VALUE1 | VALUE2 | VALUE3 | position | i | v |
|-------|-------|-------|--------|--------|---------|----------|----|------|
| 33 | 25 | 10 | nice | hello | goodbye | 1 | 33 | nice |
| 10 | 15 | 28 | dice | hay | bird | 1 | 10 | dice |
http://sqlfiddle.com/#!9/9086d5/4
最終ステップ - ORDER BY i DESC LIMIT 1
を用いi
に最高値を持つ行をピック:
select `INT_1`, `INT_2`, `INT_3`, `VALUE1`, `VALUE2`, `VALUE3`
from (
select t.*, 1 as position, INT_1 as i, VALUE1 as v from my_table t
union all
select t.*, 2 as position, INT_2 as i, VALUE2 as v from my_table t
union all
select t.*, 3 as position, INT_3 as i, VALUE3 as v from my_table t
) n
where v like '%ice%'
order by i desc
limit 1
結果:
を
| INT_1 | INT_2 | INT_3 | VALUE1 | VALUE2 | VALUE3 |
|-------|-------|-------|--------|--------|---------|
| 33 | 25 | 10 | nice | hello | goodbye |
http://sqlfiddle.com/#!9/9086d5/5
あなたはWHERE
の代わりにHAVING
句を使用する場合は、サブクエリを使用する必要はありませんので、クエリは、短くすることができます。しかし、必要がないかもしれない2つの列(i
とv
)が得られます。一方、あなたが必要とする唯一の列であるかもしれません。
select t.*, INT_1 as i, VALUE1 as v from my_table t union all
select t.*, INT_2 as i, VALUE2 as v from my_table t union all
select t.*, INT_3 as i, VALUE3 as v from my_table t
having v like '%ice%'
order by i desc
limit 1
とパフォーマンスを少し改善するかもしれないもう一つの変更:
select t.*, INT_1 as i from my_table t where VALUE1 like '%ice%' union all
select t.*, INT_2 as i from my_table t where VALUE2 like '%ice%' union all
select t.*, INT_3 as i from my_table t where VALUE3 like '%ice%'
order by i desc
limit 1
本当にMySQLを使用していますか? –