I have two tables :
user
=======
id
name
class
marks
=======
id
user_id
sub_id
mark
user table contains the details of user (student) marks table contains the marks of a student in different subjects with subject id
I want to fetch name, class and total marks from these tables.
I have two queries :
1. SELECT name, class, SUM(mark) AS total FROM user
LEFT JOIN marks ON marks.user_id = user.id
GROUP BY marks.user_id
///Here in GROUP BY I have used foreign key (marks.user_id)
2. SELECT name, class, SUM(mark) AS total FROM user
LEFT JOIN marks ON marks.user_id = user.id
GROUP BY user.id
///Here in GROUP BY I have used primary key (user.id)
Both gives me required data. My question is which one should I use?
Is there any rule which says you should use primary key in group by OR foreign key in group by OR something like that ?
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
Grouping by primary key results in a single record in each group which is logically the same as not grouping at all / grouping by all columns, therefore we can select all other columns.
A primary key is used to ensure data in the specific column is unique. A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It uniquely identifies a record in the relational database table.
Since each foreign key value must exactly match the corresponding primary key value, the foreign key must contain the same number and data type of columns as the primary key, and these key columns must be in the same order. A foreign key can also have different column names than the primary key.
Given you have done a left join you should use the 2nd query as marks.user_id could be null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With