2013-03-11 78 views
1

我有兩個具有一對多關係的表。我通過id列加入表格。我的問題是我需要從第二個(tablekey_id)表中的所有匹配項的計數,但我需要從布爾is_basedomain標記的行中的信息。作爲說明,只有一行is_basedomain = 1,每行同一個tablekey_id。選擇連接表的行數

表:tablekey

id linkdata_id timestamp 
22 9495028175 2013-03-10 01:13:46 
23 8392740179 2013-03-10 21:23:25 

表:searched_domains。

注意:tablekey_id是tablekey表中id的外鍵。

id tablekey_id domain  is_basedomain 
1 22   somesite.com 1 
2 22   yahoo.com  0 
3 23   red.com  1 
4 23   blue.com  0 
5 23   green.com  0 

繼承人查詢我正在使用。我試圖使用子查詢,但我似乎不能選擇當前tablekey_id的計數,所以這是行不通的。

SELECT `tablekey_id`, `linkdata_id`, `timestamp`, `domain`, `is_basedomain`, 
    (SELECT COUNT(1) AS other FROM `searched_domains` AS dd 
    ON dd.tablekey_id = d.tablekey_id GROUP BY `tablekey_id`) AS count 
FROM `tablekey` AS k 
JOIN `searched_domains` AS d 
ON k.id = d.tablekey_id 
WHERE `is_basedomain` = 1 GROUP BY `tablekey_id` 

,我想找回的是結果:

tablekey_id linkdata_id timestamp   domain  is_basedomain count 
22   9495028175 2013-03-10 01:13:46 somesite.com 1    2 
23   8392740179 2013-03-10 21:23:25 red.com  1    3 

誰能幫助我進入一個查詢呢?

回答

4

你可以把那些is_basedomain = 1,查詢中一個單獨的表中searched_domains行,並與searched_domains的另一個實例加入它(獲取數):

SELECT 
    d.tablekey_id, 
    k.linkdata_id, 
    k.timestamp, 
    d.domain, 
    d.is_basedomain, 
    COUNT(*) as 'count' 
FROM 
    tablekey AS k 
     join searched_domains AS d on d.tablekey_id=k.id 
     join searched_domains AS d2 on d2.tablekey_id=d.tablekey_id 
WHERE 
    d.is_basedomain = 1 
GROUP BY 
    d.tablekey_id, 
    k.linkdata_id, 
    k.timestamp, 
    d.domain, 
    d.is_basedomain 
3

您使用ON時改用WHERE

試試這個

SELECT `tablekey_id`, `linkdata_id`, `timestamp`, `domain`, `is_basedomain`, 
    (SELECT COUNT(1) AS other FROM `searched_domains` AS dd 
    where dd.tablekey_id = d.tablekey_id GROUP BY `tablekey_id`) AS count 

    FROM `tablekey` AS k 
    JOIN `searched_domains` AS d 
    ON k.id = d.tablekey_id 
    WHERE `is_basedomain` = 1 GROUP BY `tablekey_id` 

DEMO HERE

1

沒有理由使用子查詢,或者您有什麼看法有一個錯誤?

SELECT 
    `tablekey_id`, 
    `linkdata_id`, 
    `timestamp`, 
    `domain`, 
    `is_basedomain`, 
    COUNT(*) as count 
FROM 
    `tablekey` AS k , 
    `searched_domains` AS d 
WHERE 
    k.id = d.tablekey_id AND 
    `is_basedomain` = 1 
GROUP BY 
    `tablekey_id`, 
    `linkdata_id`, 
    `timestamp`, 
    `domain`, 
    `is_basedomain` 

如果你只想要最新的時間戳使用MAX(timestamp) as timestampgroup by刪除它。

+0

不會產生正確的結果searled_domains僅限於其中is_basedomain = 1的那些行。這將產生不正確的結果來計算列。 – slaakso 2013-03-11 12:29:51

+0

@slaakso我不明白。我嘗試了你的和我的查詢在sql小提琴http://sqlfiddle.com/#!2/fdecf/3 – iiro 2013-03-11 12:37:48

+0

好吧,也許我現在理解了問題後編輯。你和echo_me的查詢給出了不同的結果。我會檢查發生了什麼:) – iiro 2013-03-11 12:42:13