我有两张 table 。一张表基于“标识符”存储用户的元数据,“标识符”是用于识别访问者的唯一字符串。
另一个表存储对网站的每次点击,以及是否设置了操作。 “操作”可以是普通的“查看”、“下载”或“PDF”(当用户下载 PDF 时发生)。每个页面都有一个带有 post_id 的标识符以供引用。
结构:
标识符元
- ID
- meta_key
- meta_value
- identifier
痕迹
- ID
- created_at
- identifier
- ipaddress
- action
- post_id
因此,我想运行一个查询,选择附加到一个或多个“post_ids”的所有跟踪,按标识符分组并在某个时间戳范围之间。我只想要“identifier_meta”中存在任何元的记录,并且我想计算所有操作(这可能是硬编码的,因为只有 6 个操作:
- download
- download-word
- download-pdf
- view
SELECT *
FROM wp_traces
WHERE
identifier IN ( SELECT identifier FROM wp_identifier_meta )
AND
created_at > 0
AND
created_at < 102030502
AND
(
post_id = 1
OR
post_id = 2
)
GROUP BY identifier
ORDER BY created_at
这为我提供了属于某些帖子的特定日期和时间之间的痕迹,但我错过了结果集中标识符的操作计数...坦率地说,我不知道如何添加它。
理想情况下,我有每行包含的结果集
- traces.identifier (string)
- identifier_meta.name (string (can be empty)
- identifier_meta.company (string) (can be empty)
- traces.created_at (date last trace)
- SUM of total download within this date
- SUM of total download-word within this date
- SUM of total download-pdf within this date
- SUM of total email within this date
- SUM of total view within this date
- SUM of total print within this date
最佳答案
听起来您需要将 case 语句与 SUM 聚合函数结合使用。像这样的东西。由于我不知道您数据的确切性质,因此我进行了一些猜测。
SELECT t.identifier,
im.name,
im.company,
t.created_at,
SUM(CASE WHEN meta_value = 'download' THEN 1 ELSE 0 END) AS total_downloads,
SUM(CASE WHEN meta_value = 'download-word' THEN 1 ELSE 0 END) AS total_downloads,
SUM(CASE WHEN meta_value = 'download-pdf' THEN 1 ELSE 0 END) AS total_downloads,
SUM(CASE WHEN meta_value ='email' THEN 1 ELSE 0 END) AS total_downloads,
SUM(CASE WHEN meta_value ='view' THEN 1 ELSE 0 END) AS total_downloads,
SUM(CASE WHEN meta_value ='print' THEN 1 ELSE 0 END) AS total_downloads
FROM wp_traces AS t
JOIN wp_identifier_meta AS im
ON t.identifier = im.identifier
WHERE
t.created_at > 0
AND
t.created_at < 102030502
AND
(
t.post_id = 1
OR
t.post_id = 2
)
GROUP BY t.identifier
ORDER BY created_at
关于php - 具有复杂计数的多集 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28237211/