计算mysql中两个表的问题

时间:2013-04-10 11:04:34

标签: mysql count

我想从两张桌子中获得少于3张照片的记录数量。这是我尝试过的但是效果不佳

SELECT
    SUM(tot_rent) AS tot_rent
    FROM (
    SELECT
            COUNT(id) AS tot_rent
        FROM crm_rentals_images
        GROUP BY rentals_id
        HAVING COUNT(*) <3
    UNION
    SELECT
            COUNT(id) AS tot_rent
        FROM crm_sales_images
        GROUP BY rentals_id
        HAVING COUNT(*) <3
    ) s

缺少什么?当我与真实数据进行比较时,它没有显示正确的结果

CREATE TABLE IF NOT EXISTS `crm_rentals_images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(22) NOT NULL,
`rentals_id` int(22) DEFAULT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

INSERT INTO `crm_rentals_images` (`id`, `image`, `rentals_id`) VALUES
(1, 'a.jpg', 1),
(2, 'b.jpg', 1),
(3, 'a.jpg', 1),
(4, 'b.jpg', 1),
 (5, 'a.jpg', 2),
(6, 'b.jpg', 2),
(7, 'a.jpg', 4),
(8, 'b.jpg', 4),
(9, 'a.jpg', 3),
(10, 'b.jpg', 3);

1 个答案:

答案 0 :(得分:0)

尝试这样的查询

select
  count(id) as tot_rent
from (
    select
        count(id) as tot_rent
    from crm_rentals_images
    GROUP BY rentals_id
    HAVING tot_rent < 3 
    union ALL
    select
        count(id) as tot_rent
    from crm_sales_images
    GROUP BY rentals_id
    HAVING tot_rent < 3
    ) s
group by tot_rent