gpt4 book ai didi

MySQL 查询 : GROUP BY without loosing rows in result

转载 作者:可可西里 更新时间:2023-11-01 08:26:34 25 4
gpt4 key购买 nike

我已经编写了一个 MySQL 查询,但我对输出不太满意。

查询看起来像这样:

SELECT 
f.id,
s.time,
f.name,
f.value
FROM
entries s,
entry_details f
WHERE
f.id = s.id AND (f.name = 'fruit' OR f.name = 'vegetable');

并产生这个结果:

id | time       | name      | value
---|------------|-----------|--------
4 | 2016-01-14 | fruit | banana
4 | 2016-01-14 | vegetable | carrot
5 | 2016-01-14 | fruit | apple
5 | 2016-01-14 | vegetable | corn

虽然所需的所有信息都在那里,但我想知道是否有办法将 f.id 的所有结果放在一行中?

使用 GROUP BY f.id 我实现了我想要的,但是 vegetable 行消失了。

这甚至可以单独使用 MySQL 吗?

最佳答案

是的,但是您需要组合(聚合)剩余列:

SELECT 
f.id,
MAX(s.time) AS `time`,
GROUP_CONCAT(f.name) AS `name`,
GROUP_CONCAT(f.value) AS `value`
FROM entries s
JOIN entry_details f
ON f.id = s.id
WHERE f.name IN('fruit', 'vegetable')
GROUP BY f.id;

避免使用旧的逗号连接语法,改用新的 JOIN

输出:

╔════╦════════════╦═════════════════╦════════════════╗
║ id ║ time ║ name ║ value ║
╠════╬════════════╬═════════════════╬════════════════╣
║ 4 ║ 2016-01-14 ║ fruit,vegetable ║ banana, carrot ║
║ 5 ║ 2016-01-14 ║ fruit,vegetable ║ apple, corn ║
╚════╩════════════╩═════════════════╩════════════════╝

关于MySQL 查询 : GROUP BY without loosing rows in result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com