Question

Suppose I've got two tables

TABLE A
id     name
1      emon
2      sumon
3      mamun
4      bonna
5      ferdousi

TABLE B
id     name_id score
1      1       100
2      2       0
3      2       10
4      3       50
5      3       60

I want this DATA

name    score
emon    100
sumon   0
sumon   10
mamun   50
mamun   60

I know this is easy query, just like:

SELECT A.name, B.score FROM A 
RIGHT JOIN B
ON A.id=B.name_id

but this query not work when I set foreign key

SELECT sum(B.score) FROM A 
RIGHT JOIN B
ON A.id=B.name_id
group by B.name_id

My question is how can I set foreign key in this situation? I know in relational database, without relation may be not good decision. In this situation GROUP BY clause not work when i set foreign key. Any good idea?

Was it helpful?

Solution

Answer to the revised question

Paraphrasing the question:

Why does this query not work against the schema?

SELECT sum(B.score) FROM A 
RIGHT JOIN B
ON A.id=B.name_id
GROUP BY B.name_id

Part of the answer must be "in what way does it 'not work'?" As written, the query should produce an answer row for every row in B.

100
 10
110

The RIGHT OUTER JOIN (ROJ) really doesn't make any difference to the query result; you could as well have omitted the keyword RIGHT and would get the same result:

SELECT SUM(B.score)
  FROM A 
  JOIN B ON A.id = B.name_id
 GROUP BY B.name_id

If, as seems plausible, you want the name and aggregate score for each player listed in table A, then you'd write:

SELECT A.Name, SUM(B.Score) AS TotalScore
  FROM A
  LEFT JOIN B ON A.id = B.Name_ID
 GROUP BY A.Name

The RIGHT OUTER JOIN has been replaced by a LEFT OUTER JOIN. This will list all the players.

Answer to the original version of the question

The original question applied to the schema shown and asked:

My question is how can I set a foreign key in this situation?

  1. You will have a primary key on TableA(ID).
  2. You will have a primary key on TableB(ID).
  3. You will create a foreign key on TableB(Name_ID) that references TableA(ID).

OTHER TIPS

You would set a foreign key on B.name_id referencing A.id.

In MySQL this would be done like:

ALTER TABLE B ADD FOREIGN KEY (name_id) REFERENCES A(id)

Note: If you do not already have an index on name_id, you should create this first.

In this situation A.id is the column that has to be unique. I'm guessing it is already the primary key of table A though so this is not a problem.

The benefit of having a foreign key is it maintains referential integrity. That is, you are guaranteed that every name_id in B actually refers to an existing record in A. Without a foreign key, you would be able to insert the row name_id=999, score=50 in B, which refers to nobody. With a foreign key, the database engine will reject this insert.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top