简体   繁体   English

用MySQL中的两个表计数问题

[英]Count issue with two tables in mysql

i want to get number of records from two tables having less than 3 pics.here is what i have tried but this is not working well 我想从两个少于3个pics.table的表中获取记录数,这是我尝试过的方法,但是效果不佳

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

what is missing?when i am comparing with real data,it do not show correct result 缺少什么?当我与真实数据进行比较时,它没有显示正确的结果

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);

Try your query like this 像这样尝试查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM