大多数情况下应该避免为表名取别名
给表名取缩写看起来很诱人,比如 users
缩写为 u
,charges
缩写为 c
,但是这将会降低 SQL 的可读性:
-- Good
select
users.email,
sum(charges.amount) as total_revenue
from users
inner join charges on users.id = charges.user_id
-- Bad
select
u.email,
sum(c.amount) as total_revenue
from users u
inner join charges c on u.id = c.user_id
大多数情况下你都应该输入完整的表名,只有两个例外:
- 如果你需要在同一个查询中多次连接到同一个表,并且需要区分每个版本,则需要使用别名;
- 如果你使用的是长的或模棱两可的表名,那么为它们取表名会很有用,但仍然需要使用有意义的名词。
-- Good: 有意义的别名
select
companies.com_name,
beacons.created_at
from stg_mysql_helpscout__helpscout_companies companies
inner join stg_mysql_helpscout__helpscout_beacons_v2 beacons
on companies.com_id = beacons.com_id
-- OK: 没有别名
select
stg_mysql_helpscout__helpscout_companies.com_name,
stg_mysql_helpscout__helpscout_beacons_v2.created_at
from stg_mysql_helpscout__helpscout_companies
inner join stg_mysql_helpscout__helpscout_beacons_v2
on stg_mysql_helpscout__helpscout_companies.com_id =
stg_mysql_helpscout__helpscout_beacons_v2.com_id
-- Bad: 不清晰的别名
select
c.com_name,
b.created_at
from stg_mysql_helpscout__helpscout_companies c
inner join stg_mysql_helpscout__helpscout_beacons_v2 b
on c.com_id = b.com_id