1

我有两个具有一对多关系的表。我通过 id 列加入表格。我的问题是我需要计算第二个(tablekey_id)表中所有匹配条目的数量,但我需要标有 boolean 的行中的信息is_basedomainis_basedomain请注意,每组具有相同 tablekey_id 的行只有一行= 1。

表:表键

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

3 回答 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
于 2013-03-11T12:28:00.070 回答
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`

在这里演示

于 2013-03-11T12:13:15.353 回答
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 timestamp并将其从group by.

于 2013-03-11T12:14:34.087 回答