计数子查询

时间:2010-09-09 01:42:55

标签: sql

比方说,我有这张表:

Items:
-------
id
title
price

我想创建一个创建新行的查询,对于每个项目,它将查询与id匹配的另一个表,另一个表中的id,在另一个表中将该行设置为另一行。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

select
    ThisTable.id,
    title,
    price,
    other_count
from
(
    select
        id,
        count(*) as other_count
    from OtherTable
    group by id
) OtherTableCount
    inner join ThisTable
        on ThisTable.id = OtherTable.id

答案 1 :(得分:0)

你说你想要“选择id,标题,计数(从otherTable中选择x,otherTable.id = thisTable.id)作为来自thisTable的new_rows”

我认为您需要像

这样的分组连接
select
    id,
    title,
    count(*)
from
    thisTable,
    otherTable
where
    (otherTable.foreignRefKey = thisTable.id)
group by
    id,
    title

我认为那会这样做。如果otherTable没有引用thisTable

的记录,请使用外连接