简体   繁体   English

SELECT * 列的 MySQL 别名

[英]MySQL alias for SELECT * columns

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.* ):这是我想要获得的数据(同时仍然使用SELECT u.*, u2.* ):

|  id  | name |  brother_id  | brother_name |
   1     john        2             alex

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:所以不幸的是,如果你有很多列,你需要去:

SELECT u.col1 AS u_col1
    , u.col2 AS u_col2
    , u.col3 AS u_col3
    -- etc
    , u2.col1 AS u2_col1
    , u2.col2 AS u2_col2
    , u2.col3 AS u2_col3
    -- etc
FROM table1 AS u
-- INNER JOIN / LEFT OR RIGHT OUTER JOIN / ,
    table2 AS u2

Try using a UNION query:尝试使用UNION查询:

eg例如

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

你不能只使用SELECT *然后在你的代码中引用u.field1u2.field2吗?

SELECT alias.* 确实适用于 mysql >= 5.6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM