MySQL 根据 WHERE 子句更改虚拟列
MySQL change virtual column based on WHERE clause
是否可以根据 where 子句更改虚拟列值?
我有这个table:
[computername] [computerlocation] [starttime] [endtime]
computer, siteA, 1457537657, 1457532657
computer2, siteB, 1457547657, 1457546657
computer3, siteB, 1457237657, 14575237657
我想看看在给定站点和给定时间范围内有多少台计算机,我目前使用的查询是:
select count(*), computerlocation
from table
where site like "site%"
and starttime <= "1457532657" and endtime >= "1457532657"
group by computerlocation
但是,目前我必须 运行 此查询数百次才能创建一个图表,显示一段时间内有多少台计算机。
是否可以做这样的事情:
select count(*), computerlocation, "null" as time
from table
where site like "site%"
and ( (starttime <= "1457532657" and endtime >= "1457532657" as time="timeA")
OR (starttime <= "1457532357" and endtime >= "1457532357" as time="timeB")
OR (starttime <= "1457532651" and endtime >= "1457532651" as time="timeC")
)
group by time, computerlocation
您使用 CASE
表达式
首先创建虚拟列,然后执行 group by
SELECT time_group, computerlocation, count(*)
FROM (
SELECT computerlocation,
CASE WHEN (starttime <= '1457532657' and endtime >= '1457532657') THEN 'timeA'
WHEN (starttime <= '1457532357' and endtime >= '1457532357') THEN 'timeB'
WHEN (starttime <= '1457532651' and endtime >= '1457532651') THEN 'timeC'
ELSE 'N/A'
END as time_group
from table
where site like 'site%'
) T
GROUP BY time_group, computerlocation
btw 双引号表示 "fieldname"
单引号表示字符串 'string'
你应该检查BETWEEN
比较器,应该写成
WHERE '1457532657' BETWEEN starttime AND endtime
是否可以根据 where 子句更改虚拟列值?
我有这个table:
[computername] [computerlocation] [starttime] [endtime]
computer, siteA, 1457537657, 1457532657
computer2, siteB, 1457547657, 1457546657
computer3, siteB, 1457237657, 14575237657
我想看看在给定站点和给定时间范围内有多少台计算机,我目前使用的查询是:
select count(*), computerlocation
from table
where site like "site%"
and starttime <= "1457532657" and endtime >= "1457532657"
group by computerlocation
但是,目前我必须 运行 此查询数百次才能创建一个图表,显示一段时间内有多少台计算机。
是否可以做这样的事情:
select count(*), computerlocation, "null" as time
from table
where site like "site%"
and ( (starttime <= "1457532657" and endtime >= "1457532657" as time="timeA")
OR (starttime <= "1457532357" and endtime >= "1457532357" as time="timeB")
OR (starttime <= "1457532651" and endtime >= "1457532651" as time="timeC")
)
group by time, computerlocation
您使用 CASE
表达式
首先创建虚拟列,然后执行 group by
SELECT time_group, computerlocation, count(*)
FROM (
SELECT computerlocation,
CASE WHEN (starttime <= '1457532657' and endtime >= '1457532657') THEN 'timeA'
WHEN (starttime <= '1457532357' and endtime >= '1457532357') THEN 'timeB'
WHEN (starttime <= '1457532651' and endtime >= '1457532651') THEN 'timeC'
ELSE 'N/A'
END as time_group
from table
where site like 'site%'
) T
GROUP BY time_group, computerlocation
btw 双引号表示 "fieldname"
单引号表示字符串 'string'
你应该检查BETWEEN
比较器,应该写成
WHERE '1457532657' BETWEEN starttime AND endtime