内联接获得两个名称列,带有来自其他表格的ID
我有这个代码
SELECT
home, away, teams.name as home_name, teams.abbreviation as home_abbr, teams.name as away_name, teams.abbreviation as away_abbr
FROM
games
INNER JOIN
teams ON games.home = teams.id
WHERE
games.date >= '2022-01-01'
,此结果
我有两个表“游戏”和“团队”。在“游戏”表中有主页和客场列。那里只写ID团队。在“团队”表中,有名称,Abbriviation,Icon和其他信息。我需要从“团队”桌子上获得联合查询的回家和外客团队的名字和范围。在我的情况下,只有一个(家庭或外出)列信息
I have this code
SELECT
home, away, teams.name as home_name, teams.abbreviation as home_abbr, teams.name as away_name, teams.abbreviation as away_abbr
FROM
games
INNER JOIN
teams ON games.home = teams.id
WHERE
games.date >= '2022-01-01'
and this result
I have two tables "games" and "teams". In "games" table have home and away columns. There only wrote id team. In "teams" table have name, abbriviation, icon and other information. I need get home and away teams names and abbriviations with union query from "teams" table. In my situation get only one (home or away) column information
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您需要“查找”的“游戏”中有两个值。这意味着您需要两个加入才能获得家庭和外观的不同值。
假设
远离
fromteams
表...我们只有两次与游戏一起加入“主队”数据,然后曾获得“客场团队”数据。我们需要别名每个加入“ H”(HOME)“ A”(远)
然后更新字段以使用正确的别名。
给我们:
注意:
为了清楚起见,我将所有3个表和每个字段都列为选择/join/where/where
出色的问题
您说:“需要从“ Teams” Table的Union查询中取得回家和外客团队的名字和缩写。
为什么根本需要一个工会?这是您认为您可以获得两个团队名称/缩写的方式吗?如果是这样,这种方法对我来说是没有意义的,因为加入就足够了。除非您正在寻找不同行上的游戏结果:您的示例输出未显示。因此,我认为工会是错误的方法,鉴于所需的结果。这并不是说这不能与工会,最大和一个团体相关。但是,这比简单的加入更多的工作和可能较慢。
The issue is you have two values of teams in the "game" you need to "lookup". This means you need two joins in order to get the different values for home and away.
Assuming
home
andaway
foreign key ID's fromteams
table...We simply join from games twice, once for the "home team" data, and once for the "away team" data. We will need to alias each join "h" (home) "a" (away)
and then update fields to use the correct alias.
Giving us:
Note:
For clarity I aliased all 3 tables and each of the fields in select/join/where
Outstanding questions
You said, " need get home and away teams names and abbreviations with union query from "teams" table."
Why is a union needed at all? Was this how you thought you could get both teams names/abbreviations? If so this approach doesn't make sense to me as a Join will suffice. unless you're looking for results for a game on different lines: which your example output didn't show. So i think union is the wrong approach given desired results. This isn't to say it couldn't be done with a union and a max and a group by; but it's more work and likely slower than a simple join.