简体   繁体   English

SQL Server:相同的列但不同的值

[英]SQL Server: same column but different values

I have two tables: Users and Messages .我有两个表: UsersMessages

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.我担心Users.Username重复两次,我不确定这会显示正确的结果。

Please help me to create a proper select sentence.请帮助我创建一个正确的选择句子。

It is not different values.它不是不同的值。 There is no join defined so it will fall down to ONE join condition, outputting the values two times.没有定义连接,因此它将下降到 ONE 连接条件,输出值两次。 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 (ie TWO inner join statements)连接两次(即两个内部连接语句)
  • Both joins having other name aliases (ie AS Users_To and As Users_From AND两个连接都具有其他名称别名(即 AS Users_To 和 As Users_From AND
  • obviously getting the name from both aliases and not the table name.显然从两个别名而不是表名中获取名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM