首先使用UNION ALL
标准化表格。这意味着每一行都必须分成三份。每组一个(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
查询可短,如果你使用HAVING
条款,而不是WHERE
,所以你不需要使用子查询。但是,你会得到两列(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吗? –