我有一个带有以下列的MySQL数据库表
ID
status (can contain values 0, 1, 2)
timepstamp
text
note
owner
我想从表格中获取有关非特定所有者条目的以下信息:
number of entries
number of entries where status=0
number of entries where status=1
number of entries where status=2
number of entries where LENGTH(note)>0
minimum timestamp
maximum timestamp
我曾经阅读完整的数据集,然后使用
用PHP评估它们SELECT status, timestamp, LENGTH(note)>0 WHERE owner="name";
我遇到的问题是,有些用户有这么多条目,如果我将数据读入PHP,我经常会出现内存不足错误。我认为让MySQL评估数据应该更有效。我无法编写可以完成此任务的查询。
SELECT
MIN(timestamp) AS mintime,
MAX(timestamp) AS maxtime,
COUNT(*) AS number,
...
WHERE owner="name"
是否有可能一次性获得结果?例如,嵌套的WHERE或IF在COUNT?
中 COUNT(WHERE status=0) AS inactive
COUNT(IF(status=1)) AS active
...
你会如何解决这个问题?
答案 0 :(得分:3)
试一试 -
SELECT
COUNT(*) AS total,
SUM(IF(status=0, 1, 0)) AS stat0,
SUM(IF(status=1, 1, 0)) AS stat1,
SUM(IF(status=2, 1, 0)) AS stat2,
SUM(IF(LENGTH(note)>0, 1, 0)) AS notes,
MIN(timestamp) AS mintime,
MAX(timestamp) AS maxtime
FROM tbl_name
WHERE owner="name"
GROUP BY owner
答案 1 :(得分:0)
试试这个:
SELECT
MIN(`timestamp`) AS `mintime`,
MAX(`timestamp`) AS `maxtime`,
COUNT(`ID`) AS `number`,
(SELECT COUNT(`ID`) FROM `Table` WHERE `owner` = 'owner' AND `status` = 0) AS `inactive`,
(SELECT COUNT(`ID`) FROM `Table` WHERE `owner` = 'owner' AND `status` = 1) AS `active`,
(SELECT COUNT(`ID`) FROM `Table` WHERE `owner` = 'owner' AND LENGTH(`note`)>0) AS `longentries`
FROM `Table`
WHERE `owner` = 'name'
您应该考虑规范化数据库设计,这样您就可以有两个单独的表,一个用于用户,一个用于条目,如下所示:
USERS ID 名称 状态
ENTRIES ID 用户身份 时间戳 文本 note(如果这是特定于条目的字段;否则将其移至表USERS)
希望这有帮助。