Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY foreign key or primary key?

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 ?

like image 792
Prasanth Bendra Avatar asked Jul 22 '13 09:07

Prasanth Bendra


People also ask

When should a foreign key be a primary key?

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.

Can you group by primary key in SQL?

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.

What is the difference between foreign key and primary key?

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.

Does a foreign key have to match a primary key?

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.


1 Answers

Given you have done a left join you should use the 2nd query as marks.user_id could be null

like image 91
noz Avatar answered Oct 07 '22 11:10

noz