2013-07-05 73 views
0

我有以下兩個查詢連接兩個查詢使用連接mysql中

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

'JOIN'或'UNION'? –

+0

使用連接不工會 – Garry

回答

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 
+0

謝謝@Stephan ..這工作完美,因爲我想.ta – Garry

+0

@gurpreetsingh:高興我可以幫助:)歡呼 – Stephan

+0

我怎麼可以在cakephp分頁使用您的查詢?我是cakephp新和不到很多這個..感謝 – Garry