我如何将 where 子句与计算列一起使用以仅获取相关记录

How I use where clause with computed column to get related records only

我阅读了这个 FAQ http://www.firebirdfaq.org/faq289/ 并且我想使用 select 从当前记录中计算详细记录所以我尝试了这个

((
select count(*) from detail_table where detail_table.id = id
))

但我没有得到正确的值我得到了像 19 这样的数字,实际上它是 detail_table 中的记录总数!我怎样才能只得到主table中与当前主记录相关的记录数?

问题是 id 指的是 detail_tableid 列,而不是主 table 的列。所以它相当于:

select count(*) from detail_table where detail_table.id = detail_table.id

这意味着您只是在计算所有行数。相反 - 假设 master table 是 master_table - 你应该使用:

select count(*) from detail_table where detail_table.id = master_table.id

请注意,正如您 link 在常见问题解答中提到的那样,在引用其他 table 时,您真的应该考虑使用视图而不是计算列,因为它不太适合性能。

等效视图类似于

CREATE OR ALTER VIEW master_with_detail_count
AS
SELECT master_table.id, coalesce(c.detail_count, 0) as detail_count
FROM master_table
LEFT JOIN (SELECT id, count(*) as detail_count FROM detail GROUP BY id) c
    ON c.id = master.id