MySQL加入SELECT COUNT()

时间:2013-05-31 14:18:58

标签: mysql sql

我希望在多个表中选择结果,但我只想根据已加入COUNT()查询的SELECT结果返回行。

以下是查询当前的显示方式:

SELECT `s`.`venue_id` AS `id`,
       CONCAT(`u`.`First_name`, ' ', `u`.`Surname`) AS `user_name`,
       `u`.`avatar` AS `avatar`,
       `u`.`facebookId` AS `fid`,
       `x`.`imgs` AS `num_imgs`
       FROM `new_shortlists_venues` `s`
       INNER JOIN `new_shortlists` ON `new_shortlists`.`id` = `s`.`list_id`
       INNER JOIN `users` `u` ON `u`.`id` = `new_shortlists`.`bride_id`
       LEFT JOIN (SELECT `listing_id`, COUNT(*) `imgs` FROM `listingsImages`) `x` ON `s`.`venue_id` = `x`.`listing_id`
       WHERE `new_shortlists`.`venues` > 4
       AND `new_shortlists`.`bride_id` != 0
       GROUP BY `s`.`list_id`
       ORDER BY `s`.`date_added` DESC
       LIMIT 6

由于某种原因,查询会为NULL返回num_imgs。基本上,我只想选择listingsImages表中至少有4条记录的记录。

请注意,这是针对遗留系统的,我没有设计数据库!因此,我现在可以选择更改架构。

2 个答案:

答案 0 :(得分:2)

您离开了子查询的GROUP BY。您当前的查询返回与随机COUNT(*)关联的listing_id。添加GROUP BY listing_id,您应该返回正确的计数。

SELECT `s`.`venue_id` AS `id`,
   CONCAT(`u`.`First_name`, ' ', `u`.`Surname`) AS `user_name`,
   `u`.`avatar` AS `avatar`,
   `u`.`facebookId` AS `fid`,
   `x`.`imgs` AS `num_imgs`
   FROM `new_shortlists_venues` `s`
       INNER JOIN `new_shortlists` ON `new_shortlists`.`id` = `s`.`list_id`
       INNER JOIN `users` `u` ON `u`.`id` = `new_shortlists`.`bride_id`
       LEFT JOIN (SELECT `listing_id`, COUNT(*) `imgs` 
                  FROM `listingsImages` 
                  GROUP BY `listing_id`) `x` ON `s`.`venue_id` = `x`.`listing_id`
   WHERE `new_shortlists`.`venues` > 4
       AND `new_shortlists`.`bride_id` != 0
   GROUP BY `s`.`list_id`
   ORDER BY `s`.`date_added` DESC
   LIMIT 6

要返回至少包含4条记录的记录,只需将该约束添加到WHERE条件中:

AND `x`.`imgs` >= 4

答案 1 :(得分:0)

这可能是罪魁祸首:

ON `s`.`venue_id` = `x`.`listing_id`