我有一个查询(在MySQL中,但这是一个通用的SQL问题),如下所示:
SELECT 'Hits', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_HITS'
UNION
SELECT 'Inserts', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_INSERTS';
它产生以下结果:
+---------+----------------+
| Hits | variable_value |
+---------+----------------+
| Hits | 8330 |
| Inserts | 7075 |
+---------+----------------+
我想要得到的是这两个的比率,它们在同一SQL中。基本上,结果集如下所示:
+---------+----------------+
| Hits | variable_value |
+---------+----------------+
| Hits | 8330 |
| Inserts | 7075 |
| H/I | 1.177
+---------+----------------+
如何编写此SQL?我认为可能需要一个JOIN,但是我不确定如何为SQL中涉及的数学获取两行的 value 。感谢您的指导!
答案 0 :(得分:2)
如果您可以将它们作为三个独立的列而不是行接受,则可以执行以下操作:
select max(case when variable_name = 'QCACHE_HITS' then variable_value end) as hits,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end) as inserts,
(max(case when variable_name = 'QCACHE_HITS' then variable_value end) /,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end)
) as ratio
from global_status ;
取消这一点甚至可能是最简单的:
select h.hits,
(case when h.hits = 'hits' then hits
when h.hits = 'inserts' then inserts
else ratio
end)
from (select max(case when variable_name = 'QCACHE_HITS' then variable_value end) as hits,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end) as inserts,
(max(case when variable_name = 'QCACHE_HITS' then variable_value end) /,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end)
) as ratio
from global_status
) s cross join
(select 'hits' as hits union all
select 'inserts' union all
select 'h/i'
) x;
这看起来很复杂,但是基本上只扫描global_status
一次(尽管对于一张小桌子来说可能没什么大不了的。)
答案 1 :(得分:1)
这将起作用:
SELECT 'Hits', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_HITS'
UNION
SELECT 'Inserts', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_INSERTS'
UNION
select 'H/I',(SELECT variable_value
FROM global_status
WHERE variable_name = 'QCACHE_HITS')/(SELECT variable_value
FROM global_status
WHERE variable_name = 'QCACHE_INSERTS') as variable_value
);
答案 2 :(得分:1)
由于插入和点击的结果不同,只需合并并按如下所示划分两个单独的子查询并获得o / p
此外,联接不是必需的,因为您不需要额外的列等,而无需额外的行数据
.... UNION
Select 'H/I',(SELECT variable_value
FROM global_status
WHERE variable_name =
'QCACHE_HITS')
/
( SELECT variable_value
FROM global_status
WHERE variable_name =
'QCACHE_INSERTS')
答案 3 :(得分:1)
我已经假设您提供的代码可以解决这个问题。
SELECT 'Hits', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_HITS'
UNION
SELECT 'Inserts', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_INSERTS'
UNION
SELECT 'H/I', (
(SELECT variable_value FROM global_status WHERE variable_name='QCACHE_HITS')
/
(SELECT variable_value FROM global_status WHERE variable_name = 'QCACHE_INSERTS')
) AS 'variable_value';
在不起作用的情况下推荐。祝你好运。