使用CONCAT的MySQL查询
我有两张桌子:使用CONCAT的MySQL查询,mysql,Mysql,我有两张桌子: 类别=>类别ID,标题,说明,默认点,组 交易=>交易ID,日期时间,给予者ID,接收者ID,积分,类别ID,原因 教师奖励分数,选择一个类别(如“积极的态度和行为”)和一个理由(如“今天的优秀工作”),将一个条目放入事务表中 典型的类别行可能是: INSERT INTO `categories` (`Category_ID`, `Title`, `Description`, `Default_Points`, `Groups`) VALUES (17, 'Olympic Val
类别
=>类别ID
,标题
,说明
,默认点
,组
交易
=>交易ID
,日期时间
,给予者ID
,接收者ID
,积分
,类别ID
,原因
教师奖励分数,选择一个类别(如“积极的态度和行为”)和一个理由(如“今天的优秀工作”),将一个条目放入事务表中
典型的类别
行可能是:
INSERT INTO `categories` (`Category_ID`, `Title`, `Description`, `Default_Points`, `Groups`) VALUES
(17, 'Olympic Values', 'Please clearly state the correct Olympic Value that''s being used currently in the REASON box.', 5, '');
INSERT INTO `transactions` (`Transaction_ID`, `Datetime`, `Giver_ID`, `Recipient_ID`, `Points`, `Category_ID`, `Reason`) VALUES
(50, '2011-09-07', 35023, 90236, 5, 17, 'Excellent work during PE');
典型的交易
行可能是:
INSERT INTO `categories` (`Category_ID`, `Title`, `Description`, `Default_Points`, `Groups`) VALUES
(17, 'Olympic Values', 'Please clearly state the correct Olympic Value that''s being used currently in the REASON box.', 5, '');
INSERT INTO `transactions` (`Transaction_ID`, `Datetime`, `Giver_ID`, `Recipient_ID`, `Points`, `Category_ID`, `Reason`) VALUES
(50, '2011-09-07', 35023, 90236, 5, 17, 'Excellent work during PE');
我想使用MySQL尝试并做的是为每个类别生成一个总分列表(即SUM(transactions.points)
,还有一些示例原因
我想这得用海螺吗
我需要:
SUM(transactions.Points)
每个类别
类别。标题
- 5个独特的
交易。每个类别的原因
这可能看起来像
Points Title Sample
14252 Olympic Values Excellent work in PE!|Great display of friendship|Well done!
15532 Outstanding Effort Amazing work!|Worked so hard|Great piece!
这可能吗
提前感谢,这是您想要的GROUP\u CONCAT
您需要执行以下操作:
SELECT SUM(t.Points),
c.title,
SUBSTRING_INDEX(GROUP_CONCAT(transactions.reasons SEPERATOR '|'), '|', 5)
FROM transactions t JOIN categories c ON (t.Category_ID=c.Category_ID)
GROUP BY c.Category_ID
感谢@ChrisPatrick的回答,这是我使用的代码:
SELECT
SUM(t.Points) AS Total_Points,
c.Title,
SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT t.reason SEPARATOR '|'), '|', 5) AS Sample_Reasons
FROM
transactions t JOIN categories c ON (t.Category_ID=c.Category_ID)
GROUP BY c.Category_ID
ORDER BY c.Title ASC
Hi@ChrisPatrick。除了返回的原因不是唯一的之外,这一点很好。通常,当事务被输入数据库时,它将以30(类大小)为一批,因此前5个事务通常具有相同的“原因”.有什么可以让你的理由与众不同的吗?啊,明白了!我会把它作为答案贴出来,但会给你荣誉。