简体   繁体   English

SQL通过列号/索引/位置而不是列名选择列

[英]sql select column via column number/index/position instead of column name

How to query select column via column number/index/position instead of column name? 如何通过列号/索引/位置而不是列名查询选择列?

So far this does not work: 到目前为止,这不起作用:

SELECT 1,2,3,4,5,6,7 from table_1
Union 
SELECT 1,2,3,4,5,6,7 from table_2

If the DB supports common table expressions (all except MySQL), you can give the columns new names: 如果数据库支持公用表表达式(除MySQL以外的所有表表达式),则可以为列赋予新名称:

WITH cte(c1, c2, c3, c4, c5, c6, c7) AS (
    SELECT * FROM table_1
    UNION
    SELECT * FROM table_2
)
SELECT c1, c2, c3, c4, c5, c6, c7 FROM cte;

However, this works only if you can use SELECT * , so both tables must have the same, known number of columns. 但是,这仅在可以使用SELECT * ,因此两个表必须具有相同的已知列数。

In MySQL, you could use a view with column names instead: 在MySQL中,您可以使用带有列名的视图:

CREATE VIEW v(c1, c2, c3, c4, c5, c6, c7) AS SELECT ...;

I don't know which dbms you are using but I'm pretty sure it can't be done, and even if it is possible, I would not recommend that at all. 我不知道您使用的是哪个dbms,但是我敢肯定它无法完成,即使有可能,我也不建议这样做。 That won't save you a lot of time and I'm guessing its just comes from laziness , but in the future if someone would work on your work, he won't understand a thing. 那不会为您节省很多时间,我想这只是懒惰而已,但是将来如果有人愿意为您工作,他将一无所知。 In addition, if you'll need to change one of the columns/drop or add you are leading your self into an mess. 另外,如果您需要更改列/拖放之一或添加,则会使自己陷入混乱。 My suggestion - Use the full name 我的建议-使用全名

Just UNION the SELECTS. 只是UNION的选择。 UNION already acts the way you want. UNION已经按照您想要的方式工作。 It ignores column names in unioning rows then uses the column names from the first argument as column names for the result. 它会忽略联合行中的列名,然后将第一个参数中的列名用作结果的列名。

SELECT * from table_1
Union 
SELECT * from table_2

MySQL 5.7 Reference Manual 13.2.9.3 UNION Syntax MySQL 5.7参考手册13.2.9.3 UNION语法

The column names from the first SELECT statement are used as the column names for the results returned. 第一个SELECT语句中的列名用作返回结果的列名。 Selected columns listed in corresponding positions of each SELECT statement should have the same data type. 每个SELECT语句的相应位置中列出的所选列应具有相同的数据类型。 (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.) (例如,第一条语句选择的第一列应与其他语句选择的第一列具有相同的类型。)

Standard SQL has UNION CORRESPONDING that reorders the columns of the second table to be in the same (specified) order. 标准SQL具有UNION CORRESPONDING,它将第二个表的列重新排序为相同(指定的)顺序。

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

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