1

I have two tables: Users and Messages.

I try to write a proper select sentence, it does look like this for now:

SELECT
  Messages.Message_id,
  Messages.From_id,
  Users.Username,
  Messages.To_id,
  Users.Username,
  Messages.Date,
  Messages.Subject,
  Messages.Text,
  Messages.Picture
FROM
  Messages
INNER JOIN
  Users
ON Messages.From_id = Users.User_id
AND Messages.To_id = Users.User_id

I worry about Users.Username that repeats two times and I am not sure that this will show me a proper result.

Please help me to create a proper select sentence.

2 Answers 2

1

It is not different values. There is no join defined so it will fall down to ONE join condition, outputting the values two times. Done. If anything, this is something a code review would flag as obviously wrong - it is possible you want to show users from and to, in which case you need:

  • Join TWO times (i.e. TWO inner join statements)
  • Both joins having other name aliases (i.e. AS Users_To and As Users_From AND
  • obviously getting the name from both aliases and not the table name.
Sign up to request clarification or add additional context in comments.

2 Comments

Is that the correct one?: ``` SELECT Messages.Message_id, Messages.From_id, UsersFrom.Username, Messages.To_id, UsersTo.Username, Messages.Date, Messages.Subject, Messages.Text, Messages.Picture FROM Messages INNER JOIN Users AS UsersFrom ON Messages.From_id = UsersFrom.User_id INNER JOIN Users AS UsersTo ON Messages.To_id = UsersTo.User_id ``` Unfortunately can't test it right now, I just need to know if the way I think is correct.
Exactly. I generally NEVER use implicit joins - too much danger in them - and always define the join condition.
0

Try the below query,

SELECT
Messages.Message_id,
Messages.From_id,
FromUser.Username,
Messages.To_id,
ToUser.Username,
Messages.Date,
Messages.Subject,
Messages.Text,
Messages.Picture
FROM
Messages
INNER JOIN
Users FromUser on Messages.From_id = FromUser.User_Id
INNER JOIN
Users ToUser on Messages.To_id = ToUser.User_Id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.