0

I am having a classic case of one-to-many relation.

Currently I'm having an SQL like given below with no relation whatsoever defined between two tables (my_table and comments table):

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;

It is returning comments count in addition to other columns from my_table.

I want to correct this SQL by using 1-to-many relationship; that from my_table (one) to comments table (many).

How do I do this? Note that there are three columns used by inner query above.

Sample SQL snippet hint appreciated, thank you!

Shadow
  • 33,525
  • 10
  • 51
  • 64
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62
  • How come they have "no relation whatsoever" and still compare their columns in the subquery WHERE clause? – jarlh Aug 25 '20 at 17:38
  • I mean they are logically storing same data. But no constraints defined as such e.g. a foreign key. – Akshay Lokur Aug 25 '20 at 17:39

1 Answers1

2

Presumably, those three columns are unique in my_table, so you can declare them as a primary key:

create table my_table (
    . . . ,
    primary key (division, gl_account, document_number)
);

Then you can declare a foreign key relationship:

create table comments (
    . . . ,
    foreign key (division, gl_account, document_number) references my_table (division, gl_account, document_number)
);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786