且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL SELECT语句两次引用表

更新时间:2023-02-05 19:47:35

通常,当您想在单个查询中多次使用同一张表(大概以两种不同的能力)时,可以给表加上别名-您在FROMJOIN子句中表名称之后列出的名称:

In general, when you want to use the same table multiple times in a single query, presumably in two different capacities, you give your table an alias - a name that you list right after the table name in the FROM or JOIN clause:

SELECT h.team_name, a.team_name, g.date_played
FROM Games g
JOIN Teams h ON h.team_id = g.home_team_id
JOIN Teams a ON a.team_id = g.away_team_id
WHERE ...

gha是它们各自表的别名.

g, h, and a are aliases for their respective tables.

请注意使用JOIN语法,而不是在FROM子句中列出所有表并在WHERE子句中约束它们.这是一种更简洁的语法,应在具有联接的查询中使用.

Note the use of JOIN syntax instead of listing all tables in the FROM clause and constraining them in the WHERE clause. This is a much cleaner syntax that should be used in queries with joins.