使用mysql中的join加入两个查询

时间:2013-07-05 07:15:51

标签: mysql cakephp

我有以下两个问题

1)

SELECT  `domains`.`name` ,  `pageviews`.`domain_id` , COUNT(  `pageviews`.`domain_id` ) 
FROM  `pageviews` 
LEFT JOIN  `domains` ON (  `domains`.`id` =  `pageviews`.`domain_id` 
AND  `domains`.`user_id` =  '129' ) 
WHERE  `pageviews`.`user_id` =  '129'
GROUP BY  `pageviews`.`domain_id` 
ORDER BY COUNT(  `pageviews`.`domain_id` ) DESC 

2)

SELECT  `domains`.`name` ,  `visitors`.`ip` ,  `visitors`.`domain_id` , COUNT(  `visitors`.`domain_id` ) 
FROM  `visitors` 
LEFT JOIN  `domains` ON (  `domains`.`id` =  `visitors`.`domain_id` 
AND  `domains`.`user_id` =  '129' ) 
WHERE  `visitors`.`user_id` =  '129'
GROUP BY  `visitors`.`domain_id` 
ORDER BY COUNT(  `visitors`.`domain_id` ) DESC

我想要结合这些查询。 这是cakephp分页所必需的,因为我想在表中显示数据并想要对acc进行排序。访问者和网页浏览,如果我想。 关联是1)域名有很多访问者2)域名有很多网页浏览量

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
    pv.name,pv.domain_id,pv.counter as page_visits, v.ip, v.counter as visits
FROM (
    SELECT  `domains`.`name` ,  `pageviews`.`domain_id` , COUNT(  `pageviews`.`domain_id` ) as counter
    FROM  `pageviews` 
    LEFT JOIN  `domains` ON (  `domains`.`id` =  `pageviews`.`domain_id` 
    AND  `domains`.`user_id` =  '129' ) 
    WHERE  `pageviews`.`user_id` =  '129'
    GROUP BY  `pageviews`.`domain_id` 
    ORDER BY COUNT(  `pageviews`.`domain_id` ) DESC 
) as pv
LEFT JOIN (
    SELECT  `domains`.`name` ,  `visitors`.`ip` ,  `visitors`.`domain_id` , COUNT(  `visitors`.`domain_id` ) as counter
    FROM  `visitors` 
    LEFT JOIN  `domains` ON (  `domains`.`id` =  `visitors`.`domain_id` 
    AND  `domains`.`user_id` =  '129' ) 
    WHERE  `visitors`.`user_id` =  '129'
    GROUP BY  `visitors`.`domain_id` 
    ORDER BY COUNT(  `visitors`.`domain_id` ) DESC
) as v
    ON pv.domain_id = v.domain_id