开发者

MySQL SELECT only 1 field with AS alias

开发者 https://www.devze.com 2023-03-24 05:29 出处:网络
I\'d like to select all columns in a table, but give only one of them an alias. I have this table: id base

I'd like to select all columns in a table, but give only one of them an alias.

I have this table:

id
base
window
thickness
shading
shape
... and many more columns

Now, I want to select the base with an alias, like so: SELECT base AS structure. But I want to select all the other fields as well, without having to type them all out.

I tried SELECT *, bas开发者_C百科e AS structure, but it gives me an error.

In truth, that's not even really what I want, because I don't want base to show up at all.

Is this at all possible?


No, it isn't. Suck it up and type them all out :)


No.

You either list the ones you want, or you say "all" by writing *.

These are the two options at your disposal.

Laziness: begone! (And, let's face it, if you really need this alias, then your field is probably named wrong in the first place...)


Ultimately, you could create a VIEW to do this job transparently, but then you'd have to keep updating it as you ALTER your original table.


I was trying to avoid bringing this to your attention, but this answer does demonstrate a rounadabout way:

SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_exclude>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');

PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

(Replacing <table>, <database> and <columns_to_exclude>).

I wish to re-iterate, though: don't. Something's wrong if you have to do this.


If you don't mind also having the old name you can do something like this:

SELECT MyTable.*, MyTable.base AS structure


maybe there is a better way to solve your problem, at least the following answer works for you if you are not too lazy:

SELECT id, base AS structure, window, thickness, shading, shape ... from yourTable


as far as I know (and a check with the MySQL documentation confirmed) that it's not possible to list all the column with the original name except one, at least using *.


Inefficient, but clean, try left joining the same rows to themselves then selecting from the left join the desired column with its new name.

ie.

SELECT table_1.*, table_2.base AS structure 
SELECT 
    table_1.*, 
    table_2.base AS structure 
FROM 
    table1 AS table_1 
        LEFT JOIN table2 AS table_2 
            ON table_1.id=table_2.id


Query:

SELECT firstName AS firstStudent FROM student LIMIT 1;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号