MySQL 查询 Returns 不同的结果
MySQL Query Returns Different Results
我遇到了以下查询的奇怪问题:
SELECT
doubles_team_members.doubles_team_id,
GROUP_CONCAT(CONCAT(members.first_name,' ',members.last_name) SEPARATOR ' & ') team,
GROUP_CONCAT(DISTINCT CONCAT(members.city,', ',members.state) SEPARATOR ' & ') location,
doubles_teams.deleted_by_id
FROM
doubles_team_members
JOIN
doubles_teams USING(doubles_team_id)
JOIN
members USING(member_id)
JOIN
memberships ON members.member_id=memberships.member_id
WHERE
(memberships.expiration_date>=CURDATE() OR members.lifetime=1) AND
(doubles_teams.deleted_by_id IS NULL OR doubles_teams.deleted_by_id=0) AND
(members.deleted_by_id IS NULL OR members.deleted_by_id=0)
GROUP BY
doubles_team_members.doubles_team_id
HAVING
team='Van Williams & Derek Williams';
有时我会得到零个、一个、两个或三个结果。我应该总是得到三个结果。可能是什么原因造成的?
正如 Solarflare 所指出的,GROUP_CONCAT()
可以随机生成 team
字符串,例如'Van Williams & Derek Williams'
或 'Derek Williams & Van Williams'
.
要解决此问题,您可以 use an explicit ORDER BY
within the GROUP_CONCAT()
,例如:
GROUP_CONCAT(CONCAT(members.first_name,' ',members.last_name) ORDER BY first_name DESC SEPARATOR ' & ') team
有关示例,请参阅 documentation and this db<>fiddle。
我遇到了以下查询的奇怪问题:
SELECT
doubles_team_members.doubles_team_id,
GROUP_CONCAT(CONCAT(members.first_name,' ',members.last_name) SEPARATOR ' & ') team,
GROUP_CONCAT(DISTINCT CONCAT(members.city,', ',members.state) SEPARATOR ' & ') location,
doubles_teams.deleted_by_id
FROM
doubles_team_members
JOIN
doubles_teams USING(doubles_team_id)
JOIN
members USING(member_id)
JOIN
memberships ON members.member_id=memberships.member_id
WHERE
(memberships.expiration_date>=CURDATE() OR members.lifetime=1) AND
(doubles_teams.deleted_by_id IS NULL OR doubles_teams.deleted_by_id=0) AND
(members.deleted_by_id IS NULL OR members.deleted_by_id=0)
GROUP BY
doubles_team_members.doubles_team_id
HAVING
team='Van Williams & Derek Williams';
有时我会得到零个、一个、两个或三个结果。我应该总是得到三个结果。可能是什么原因造成的?
正如 Solarflare 所指出的,GROUP_CONCAT()
可以随机生成 team
字符串,例如'Van Williams & Derek Williams'
或 'Derek Williams & Van Williams'
.
要解决此问题,您可以 use an explicit ORDER BY
within the GROUP_CONCAT()
,例如:
GROUP_CONCAT(CONCAT(members.first_name,' ',members.last_name) ORDER BY first_name DESC SEPARATOR ' & ') team
有关示例,请参阅 documentation and this db<>fiddle。