SQL左连接自动别名?
我刚刚意识到,由于连接表中的重复列名,我将不得不开始为数据库调用添加别名。有没有办法自动告诉 SQL 给我的所有列名起别名,以便它们以表名的前缀返回?否则,当只有其中一些是别名时,就会显得相当混乱。只是试图保持一致,而不编写大量额外的代码。
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
I just realized that I'm going to have to start aliasing my database calls due to repeating column names in my join tables. Is there a way to automatically tell SQL to alias all my column names so that they are returned with a prefix of the table name? Otherwise it appears to be quite confusing when only some of them are aliased. Just trying to be consistent without writing tons of extra code.
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,但是您可以通过使用表别名让生活变得更轻松:
No, but you can make life a little easier by using table aliases:
您可以在 sql 语句中使用别名表,这样您就必须编写更少的内容,但要实际从 php 访问这些列,如果您想按名称访问它们,则无法为所有列添加别名。
您还可以从 php 访问带有索引的列,但这是维护的噩梦
you can use alias tables in your sql statements so you have to write less, but to actually access the columns from php there's no way around aliasing all of them, if you want to access them by name.
you can also access columns with indexes from php, but that's a maintenance nightmare
我建议始终为表名添加别名。如果跳过别名,后面的阅读会变得非常困难。
I would recommend to always alias table names. It makes it very hard to read later, if you skip alias.
有关信息,MySQL 5.6 中存在一个问题(可能还有其他问题!)
SELECT *
从表1
LEFT JOIN table2 ON PKI = FKI
按预期工作..但最近我在查询中将“LEFT”误拼为“LEFY”,它也可以工作,但使用标准连接!因此
SELECT *
从表1
LEFY JOIN table2 ON PKI = FKI
也可以正常工作,就像任何单词 LEFY 的替代品一样,所以要小心更改查询的拼写错误!
For info, theres a gotcha in MySQL 5.6 (possibly others!)
SELECT *
FROM table1
LEFT JOIN table2 ON PKI = FKI
works as expected.. but recently I mispelt 'LEFT' as 'LEFY' in a query and it also worked but with a standard join! so therefore
SELECT *
FROM table1
LEFY JOIN table2 ON PKI = FKI
also works just fine as does any substitute for the word LEFY, so beware a typo changing your query !!