带有多个列的mysql子查询

时间:2015-01-11 10:18:31

标签: php mysql sql subquery

我试图这样做

SELECT 
    `projects`.*,
    (SELECT 
        COUNT(`leads`.`id`),
        `pixel`.`uuid`,
        `pixel`.`project_id`
     FROM `leads` 
     LEFT JOIN `pixel` ON `leads`.`pixel` = `pixel`.`uuid`
     WHERE `projects`.`id` = `pixel`.`project_id`
     ) as leads

FROM `projects`

但我不能,因为我的子查询选择有多个列,但我必须拥有它,所以我可以进行连接,无论如何围绕这个? (我需要的只是计数) 谢谢。

3 个答案:

答案 0 :(得分:0)

将您的correlated Subquery更改为Inner Join以显示subquery

中的所有列
SELECT projects.*,
       a.*
FROM   projects P
       INNER JOIN (SELECT Count(leads.id) Cnt_id,
                          pixel.uuid,
                          pixel.project_id
                   FROM   leads
                          LEFT JOIN pixel
                                 ON leads.pixel = pixel.uuid) A
               ON projects.id = A.project_id 

答案 1 :(得分:0)

我建议你尽量避免子查询:

SELECT
  projects.*,
  IFNUL(COUNT(leads.id).0) AS Cnt_id
FROM
  projects,
  LEFT JOIN pixel ON projects.id = pixel.project_id
  LEFT JOIN leads ON leads.pixel = pixel.uuid
GROUP BY
  projects.id

我怀疑这会更快。

答案 2 :(得分:0)

这是答案

SELECT 
    `projects`.*,
    (SELECT 
        COUNT(`pixel`.`project_id`) 
    FROM `pixel` 
    WHERE `projects`.`id` = `pixel`.`project_id`) AS `num_pixels`,
    (SELECT COUNT(`leads`.`id`) FROM `leads`
                    LEFT JOIN `pixel` ON `leads`.`pixel` = `pixel`.`uuid`
                    WHERE `projects`.`id` = `pixel`.`project_id`) AS `num_leads`
FROM `projects`