问题描述
我有一个one-to-many
关系的经典案例。
目前,我正在使用下面给出的SQL,且在两个表(my_table
和comments
表)之间定义了无关联:
SELECT
(SELECT
COUNT(1)
FROM
comments
WHERE
comments.gl_account = my_table.gl_account
AND comments.document_number = my_table.document_number
AND comments.division = my_table.division) AS comments_count,my_table.division,my_table.gl_account,my_table.document_number,my_table.reviewer_group,my_table.id
FROM
my_table;
除comments
中的其他列外,它还返回my_table
个计数。
我想通过使用1-to-many
关系来更正此SQL;从my_table
(一个)到comments
表(很多)。
我该怎么做?请注意,上面的内部查询使用了三列。
感谢示例SQL代码段提示,谢谢!
解决方法
大概这三列在my_table
中是唯一的,因此您可以将它们声明为主键:
create table my_table (
. . .,primary key (division,gl_account,document_number)
);
然后您可以声明外键关系:
create table comments (
. . .,foreign key (division,document_number) references my_table (division,document_number)
);