SELECT * 列的 MySQL 别名
我正在创建一个使用来自同一个表两次的数据的视图。结果,相同的列名出现两次。
因此,我需要为这些列指定别名。如果我这样做,我会把它写成:
SELECT u.* as 'one_*', u2.* as 'two_*'
FROM users u
LEFT JOIN relationships r ON u.id=r.id_one
LEFT JOIN users u2 ON r.id_two=u2.id
但这不起作用。感谢您的帮助!
编辑:
这是我实际获取的数据:
| id | name | id | name |
1 john 2 alex
这是我想要获取的数据(同时仍然使用 SELECT u.*, u2.*
):
| id | name | brother_id | brother_name |
1 john 2 alex
I'm creating a view that is using data that comes from the same table twice. As a result, same column names appear twice.
Thus, i need to give aliases to these columns. If i were to do it, i'd write it as:
SELECT u.* as 'one_*', u2.* as 'two_*'
FROM users u
LEFT JOIN relationships r ON u.id=r.id_one
LEFT JOIN users u2 ON r.id_two=u2.id
But that doesn't work. Thanks for your help!
EDIT:
Here's the data i'm actually getting:
| id | name | id | name |
1 john 2 alex
Here's the data i'd like to get (while still using a SELECT u.*, u2.*
):
| id | name | brother_id | brother_name |
1 john 2 alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能将
*
与别名一起使用。别名可用于各个列。您必须为每个列添加别名。
因此不幸的是,如果您有很多列,则需要执行以下操作:
You can't use
*
with an alias. Aliases can be used for individual columns.You'll have to alias each column instead..
So unfortunately, if you have a lot of columns, you'll need to go:
尝试使用 UNION 查询:
例如
select a。 typeid, a.typename from MYTABLE a where a.typeid=3 UNION select a.typeid, a.typename from MYTABLE a where a.typeid=4
Try using a UNION query:
e.g.
select a.typeid, a.typename from MYTABLE a where a.typeid=3 UNION select a.typeid, a.typename from MYTABLE a where a.typeid=4
我知道这是一个老问题,但我最近遇到了这个问题并提出了解决方案。
首先查询表并获取列名
ex。
“SHOW COLUMNS FROM $table_name”
然后使用循环将前缀连接到列名
ex
foreach ($all_columns as $the_column){
$alias_select .= ', '.$table_name.'.'.$the_column['Field'].' alias_'.$the_column['字段'];
}
然后只需将此字符串放入您的查询中,您将获得另一组带有 prefix_column_name 的值。
I know this is an old question but I recently had the problem and came up with a solution.
First query the table and get the names of the columns
ex.
"SHOW COLUMNS FROM $table_name"
then use a loop to concat a prefix to the column name
ex
foreach ($all_columns as $the_column){
$alias_select .= ', '.$table_name.'.'.$the_column['Field'].' alias_'.$the_column['Field'];
}
then just put this string into your query and you will get another set of values all with the prefix_column_name.
您不能只使用
SELECT *
,然后在代码中引用u.field1
和u2.field2
吗?Can you not just use
SELECT *
and then in your code refer tou.field1
andu2.field2
?SELECT alias.* 在 mysql >= 5.6 中确实有效
SELECT alias.* does certainly work in mysql >= 5.6