SQL在连接3个表时使用count和sum

时间:2017-05-04 23:56:59

标签: mysql join

当我尝试连接2个表并使用SUM或COUNT时,它们完全按预期工作。但是,当我连接3个表时,SUM和COUNT没有任何意义,因为JOIN语句为每个表创建额外的行以具有唯一的行,因此它们会超过计数并超过所需的值。

以下是查询:

SELECT PO_club.clubid, PO_club.name, PO_club.pic, PO_club.points, count(PO_club_user.userid), SUM(PO_club_point_log.points)
FROM PO_club 
INNER JOIN PO_club_user ON PO_club.clubid = PO_club_user.clubid 
LEFT JOIN PO_club_point_log ON PO_club.clubid = PO_club_point_log.clubid 
WHERE PO_club.deleted = 0 
GROUP BY PO_club.clubid 
ORDER BY PO_club.points DESC;  

如果我运行两个单独的脚本,例如首次加入PO_club and PO_club_user以获取COUNT(),则可以正常运行。然后run PO_club JOIN PO_club_point_logSUM()一切顺利。但是,我需要运行一个脚本,这样我就不需要在前端对它进行排序。是join 3 tables还是以COUNT()只在PO_club and PO_club_users SUM PO_club and PO_club_point_log上工作private void PasteFromExcel() { DataTable tbl = new DataTable(); tbl.TableName = "ImportedTable"; List<string> data = new List<string>(ClipboardData.Split('\n')); bool firstRow = true; if (data.Count > 0 && string.IsNullOrWhiteSpace(data[data.Count - 1])) { data.RemoveAt(data.Count - 1); } foreach (string iterationRow in data) { string row = iterationRow; if (row.EndsWith("\r")) { row = row.Substring(0, row.Length - "\r".Length); } string[] rowData = row.Split(new char[] { '\r', '\x09' }); DataRow newRow = tbl.NewRow(); if (firstRow) { int colNumber = 0; foreach (string value in rowData) { if (string.IsNullOrWhiteSpace(value)) { tbl.Columns.Add(string.Format("[BLANK{0}]", colNumber)); } else if (!tbl.Columns.Contains(value)) { tbl.Columns.Add(value); } else { tbl.Columns.Add(string.Format("Column {0}", colNumber)); } colNumber++; } firstRow = false; } else { for (int i = 0; i < rowData.Length; i++) { if (i >= tbl.Columns.Count) break; newRow[i] = rowData[i]; } tbl.Rows.Add(newRow); } } DataGridView1.DataSource = tbl; }

谢谢!

1 个答案:

答案 0 :(得分:0)

这是怎么回事?这将包括所有PO_clubs,即使他们没有任何用户,以防他们有积分。如果这不是您想要的,请将第一个LEFT JOIN更改为INNER JOIN

SELECT PO_club.clubid, PO_club.name, PO_club.pic, PO_club.points, count(PO_club_user.userid), t.sum_points
FROM PO_club
LEFT JOIN PO_club_user ON PO_club.clubid = PO_club_user.clubid
LEFT JOIN
(SELECT PO_club_point_log.clubid, SUM(PO_club_point_log.points) AS sum_points
FROM PO_club_point_log INNER JOIN PO_club ON PO_club_point_log.clubid = PO_club.clubid
GROUP BY PO_club_point_log.clubid) AS t
ON PO_club.clubid = t.clubid
WHERE PO_club.deleted = 0
GROUP BY PO_club.clubid
ORDER BY PO_club.points DESC