我试图计算用户触发以下查询的次数。我已经得出结论,需要一个子查询。 以下(不可否认的是,不确定)查询的工作原理是没有子查询。 Sub Query用作独立查询。但经过三天的尝试,我无法将两者结合起来。我不知道我是否有明显的语法错误,或者我是否原则上错了。我需要帮助!
SELECT id, status, FirstName, LastName, Track, KeyChange, Version,
DATE_FORMAT(CONVERT_TZ(Created,'+00:00','+1:00'), '%l:%i %p') AS Created_formatted,
TIME_FORMAT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, pinknoise.Created, CURRENT_TIMESTAMP() - INTERVAL '0' HOUR)),'%Hh %im') AS elapsed,
(SELECT `FirstName`, Count(*) AS 'CountRequests' FROM `pinknoise` GROUP by `FirstName`)
FROM pinknoise
WHERE status = 'incoming'
ORDER BY Created DESC
答案 0 :(得分:0)
我并不真正了解您的查询应该达到的目标,但格式如下:
SELECT
id,
status,
FirstName,
LastName,
Track,
KeyChange,
Version,
DATE_FORMAT(
CONVERT_TZ(
Created,
'+00:00',
'+1:00'
),
'%l:%i %p'
) AS Created_formatted,
TIME_FORMAT(
SEC_TO_TIME(
TIMESTAMPDIFF(
SECOND,
pinknoise.Created,
CURRENT_TIMESTAMP() - INTERVAL '0' HOUR
)
),
'%Hh %im'
) AS elapsed
(
SELECT
`FirstName`,
Count(*) AS 'CountRequests'
FROM
`pinknoise`
GROUP by
`FirstName`
)
FROM
pinknoise
WHERE
status = 'incoming'
ORDER BY
Created DESC
我的想象:您希望同一个表中此特定名字的总条目数。肮脏的方式是:
SELECT
id,
status,
FirstName,
LastName,
Track,
KeyChange,
Version,
DATE_FORMAT(
CONVERT_TZ(
Created,
'+00:00',
'+1:00'
),
'%l:%i %p'
) AS Created_formatted,
TIME_FORMAT(
SEC_TO_TIME(
TIMESTAMPDIFF(
SECOND,
pinknoise.Created,
CURRENT_TIMESTAMP() - INTERVAL '0' HOUR
)
),
'%Hh %im'
) AS elapsed,
(
SELECT
Count(*)
FROM
`pinknoise` AS tb
WHERE
tb.FirstName = pinknoise.FirstName
) AS CountRequests
FROM
pinknoise
WHERE
status = 'incoming'
ORDER BY
Created DESC
更好的表现会有一个加入:
SELECT
pinknoise.id,
pinknoise.status,
pinknoise.FirstName,
pinknoise.LastName,
pinknoise.Track,
pinknoise.KeyChange,
pinknoise.Version,
DATE_FORMAT(
CONVERT_TZ(
pinknoise.Created,
'+00:00',
'+1:00'
),
'%l:%i %p'
) AS Created_formatted,
TIME_FORMAT(
SEC_TO_TIME(
TIMESTAMPDIFF(
SECOND,
pinknoise.Created,
CURRENT_TIMESTAMP() - INTERVAL '0' HOUR
)
),
'%Hh %im'
) AS elapsed,
tabA.CountRequests
FROM
pinknoise
INNER JOIN
(
SELECT
Count(*) AS 'CountRequests',
FirstName
FROM
`pinknoise`
GROUP BY
FirstName
) tabA
ON
pinknoise.FirstName = tabA.FirstName
WHERE
status = 'incoming'
ORDER BY
Created DESC
答案 1 :(得分:0)
您的子选择在选择部分中返回2个值,它只需要一个值。我猜你正在获得FirstName以进行连接。如果是这样,那么试试这个:
SELECT
p.id,
p.status,
p.FirstName,
p.LastName,
p.Track,
p.KeyChange,
p.Version,
DATE_FORMAT(CONVERT_TZ(p.Created,'+00:00','+1:00'), '%l:%i %p') AS Created_formatted,
TIME_FORMAT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, p.Created, CURRENT_TIMESTAMP() - INTERVAL '0' HOUR)),'%Hh %im') AS elapsed,
cnt.CountRequests
FROM
pinknoise p
inner join (SELECT p.FirstName, Count(*) AS CountRequests FROM pinknoise p GROUP by p.FirstName) cnt on p.FirstName = cnt.FirstName
WHERE
p.status = 'incoming'
ORDER BY
p.Created DESC;