How do I select column(s) by their “numeric” position in a table?

前端 未结 3 1562
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 13:55

I am trying to select columns by their \"x\" position in the table.

DBI

my $example = $hookup->prepare(qq{SELECT This,That,Condition,\"I also want         


        
3条回答
  •  离开以前
    2021-01-15 14:47

    You should almost NEVER rely on column number in a table in any of your code (even though you CAN theoretically do so technically).

    There are many reasons, one of the most important is that someone can always ALTER the table and insert a column in the beginning / middle, breaking your code completely.

    A second reason is that column positions - even if you assume that the table never changes - make for absolutely UNREADABLE and therefore impossible to maintain code. Will you remember that column 13 was "last_name_3" 2 years from now?

    Please note that if your problem is that for example you have something like SELECT fn11, fn12, fn13, ... fn32 in your code, and you feel like spelling out fn11..fn32 is a drag, you are not only 100% correct, but you should absolutely remove said drag via Perl idioms, as follows: "SELECT " . join(", ", map { "fn$_" } (11..32));


    Having said that, if you want to know how to do it THEORETICALLY, just as a "cool technological trick" exercise, I don't know of a good way to do it generically via DBI, but you can usually do it in database-specific way.

    To do so, you should note that:

    1. Pretty much ALL databases create tables via some sort of "CREATE TABLE" statement which takes an ORDERED list of columns (most relational databases actually physically store values in the row in that order so it's important - even if theoretical relational calculus treats columns as order-less as marcog said).

    2. Pretty much ALL da;tabases contain a special table which lists which tables contain which columns (syscolumns in Sybase, INFORMATION_SCHEMA.COLUMNS in MySQL), and that table contains numeric ID of a column which is used to order them the same as "create" order; or even special "order" field (e.g. ORDINAL_POSITION value in MySQL).

      So, you can - ahead of time - query out ordered list of columns for the table you want and their order. To query for MySQL, SELECT COLUMN_NAME, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME="XXX" . Store the data in @columns list (or if you have many tables, a hash of arrays, %columns, with table name being the key).

      Then, when building a query, you simply say

      "select $columns{table1}->[11],$columns{table1}->[13], ...."

      Please note that the actual SQL sent to the server will contain column names, BUT you will not hard-code those names anywhere in your code.

提交回复
热议问题