我如何使用带有计算列的where子句来获取相关记录

时间:2015-10-18 21:27:00

标签: sql firebird

我读了这篇FAQ http://www.firebirdfaq.org/faq289/,我想用select来计算当前记录中的详细记录,所以我尝试了这个

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

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

1 个答案:

答案 0 :(得分:2)

问题是id引用id的{​​{1}}列,而不是主表。所以它相当于:

detail_table

这意味着您只是计算所有行。相反 - 假设主表是select count(*) from detail_table where detail_table.id = detail_table.id - 您应该使用:

master_table

请注意,正如您链接到的常见问题解答中所提到的,在引用其他表时,您应该考虑使用视图而不是计算列,因为它对性能不是很好。

等效视图类似于

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