2013-03-19 63 views
0

我該如何做這樣的工作?在mysql的子查詢中使用相同的字段

INSERT INTO age.page(domain,title_count,youtube_count,ipaddress,updated) 
SELECT * FROM 
(
    SELECT domain, 
    COUNT(domain) AS titlecount, 
    (SELECT COUNT(*) FROM table2 WHERE title = table1.title) AS YoutubeCount, ipaddress 
    NOW() AS timeNow 
    FROM table1 
    GROUP BY domain 
    ORDER BY title DESC 
) a; 

我想使用子查詢來計算不同的表,但使用主查詢中相同的字段。

我想這樣做的原因是所以我不必運行兩個查詢,而不是它的唯一一個。

回答

1

你可以用第一個表做COUNT在子查詢,然後JOIN它:

INSERT INTO age.page(domain, title_count, youtube_count, ipaddress, updated) 
SELECT * FROM 
(
    SELECT 
     domain, 
     COUNT(domain) AS titlecount, 
     t2.titlecount AS YoutubeCount, 
     ipaddress, 
     NOW() AS timeNow 
    FROM table1 
    INNER JOIN 
    (
     SELECT title, COUNT(*) Titlecount 
     FROM table2 
     GROUP BY title 
    ) AS t2 ON t2.title = table1.title 
    GROUP BY domain 
    ORDER BY table1.title DESC 
) a; 
+0

我得到這個'錯誤代碼:1052列「標題」在字段列表ambiguous' – 2013-03-19 20:15:12

+1

@ DEV- Ria使用別名嘗試'table1.title'或't2.title'來解析它,而不是看我的編輯。 – 2013-03-19 20:17:46

+0

謝謝!這工作得很好! – 2013-03-19 20:20:57

相關問題