试图将计数函数添加到复杂查询PHP MYSQL中

时间:2015-04-17 09:42:26

标签: php mysql sql

我有一个包含大量内连接和左连接的复杂查询,我试图使用SQL的COUNT函数获取某个表中的记录数。

我正在尝试使用proposal_id获取每个提案的'held_proposals'表中的记录数,因为我将使用foreach循环将数据输出到表中。

从本质上讲,我想表明有多少学生针对每项提案“提出”提案。

这是我的尝试:

SELECT p.proposal_id, p.proposal_title, p.description, u.user_record_id, u.forename, u.surname, c.course_title, h.*,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags FROM proposal p 

      LEFT JOIN user u on u.user_record_id = p.user_record_id

      LEFT JOIN course_details c on c.course_code = p.course_code

      LEFT JOIN record r on r.proposal_id = p.proposal_id

      LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id

      LEFT JOIN tag_details t on t.tag_code = pt.tag_code

LEFT JOIN (
            SELECT h.student_record_id, COUNT(*) AS Held
            FROM held_proposals h
        ) H on h.proposal_id = p.proposal_id
      WHERE p.source = "Supervisor"

      AND (r.status_code not in (3,8) OR r.status_code IS NULL)

      GROUP BY p.proposal_id;

目前的表格如下:

Table for proposals

我想将表格末尾的每个提案的'held_proposals'表中返回的值添加为另一列。

请问有关如何在SQL查询中实现此目的的一些指导。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您需要将查询中的计数分组为

SELECT 
p.proposal_id, 
p.proposal_title, 
p.description, 
u.user_record_id, 
u.forename, 
u.surname, 
c.course_title, coalesce(h.Held,0) as `Held`,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags 
FROM proposal p 
LEFT JOIN user u on u.user_record_id = p.user_record_id
LEFT JOIN course_details c on c.course_code = p.course_code
LEFT JOIN record r on r.proposal_id = p.proposal_id
LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
LEFT JOIN tag_details t on t.tag_code = pt.tag_code
LEFT JOIN (
  SELECT proposal_id, COUNT(*) AS Held
  FROM held_proposals group by proposal_id
) h on h.proposal_id = p.proposal_id
WHERE p.source = "Supervisor"
AND (r.status_code not in (3,8) OR r.status_code IS NULL)
GROUP BY p.proposal_id;