PHP/MySQL: Getting Multiple Columns With the Same Name in Join Query Without Aliases?

旧时模样 提交于 2019-11-30 11:38:52

I think alias is perfect in this case

SELECT table1.column AS column1, table2.column AS column2
FROM table1
LEFT JOIN table2
ON table1.column = table2.column

To save you some typing time, use table aliases:

SELECT t1.column AS column1, t2.column AS column2
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.column = t2.column

The only way to do this without defining aliases is to fetch rows indexed by column position instead of by column name:

$sth->fetchAll(PDO::FETCH_NUM);

You could also reduce the work to alias columns by aliasing only the columns that need it:

SELECT *, posts.created_at AS postCreatedAt, posts.updated_at AS postUpdatedAt
FROM `users` LEFT OUTER JOIN `posts` ON users.id=posts.user_id

However, it's generally considered a bad idea to use SELECT * in production code anyway. You don't typically need all the columns, so just fetch those that you do need. This reduces unnecessary waste of bandwidth as you fetch results.

U can add the same qualified name after ambiguous fields (use tildas or commas)

SELECT 
   users.id `users.id`,
...
   posts.id `posts.id`, 
...
FROM `users`
   LEFT OUTER JOIN `posts` ON (users.id=posts.id)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!