总结MySQL计算字段,其中列值相同
基本上,当某个值(在我的例子中为 COMMUNICATIONS_ID)相等时,我试图对计算字段的值求和。这些分数与相同的 COMMUNICATIONS_ID 相关联,我想对这些值进行求和。
我是 SQL 新手,这是我被误导的第一次尝试:
SELECT *
FROM consumer_action_log as cal1
JOIN consumer_action_log as cal2
ON cal1.COMMUNICATIONS_ID=cal2.COMMUNICATIONS_ID
AND cal1.COMM_TYPE_ID=4
Basically, I am trying to sum up the value of a calculated field when a certain value (in my case COMMUNICATIONS_ID) are equal. These scores are associated with the same COMMUNICATIONS_ID and I want to sum up these values.
I am new to SQL and this is my misguided first attempt:
SELECT *
FROM consumer_action_log as cal1
JOIN consumer_action_log as cal2
ON cal1.COMMUNICATIONS_ID=cal2.COMMUNICATIONS_ID
AND cal1.COMM_TYPE_ID=4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为没有必要在这里将表连接到自身。
I don't see a need to JOIN the table to itself here.
即使 INNER JOIN 的结果相同,最好还是分开 ON 和 WHERE 条件。使两个表之间的联系更加清晰。
COMM_TYPE_ID=4
如果
COMMS_TYPE_ID=4
上的过滤器结果为多个cal1.COMMUNICATIONS_ID
,那么您将需要GROUP BY
COMMUNICATIONS_ID(与 cal1 或 cal2 无关 - 它们是相同的)It may be better to split the ON and WHERE conditions, even if the result is the same for INNER JOINs. Makes it clearer what links the two tables.
COMM_TYPE_ID=4
If the filter on
COMMS_TYPE_ID=4
results in multiplecal1.COMMUNICATIONS_ID
s, then you will want toGROUP BY
COMMUNICATIONS_ID (doesn't matter from cal1 or cal2 - they are the same)