In a join, how to prefix all column names with the table it came from

后端 未结 9 1778
你的背包
你的背包 2020-12-08 02:13

I\'m analysing a rather horrible legacy database/codebase, trying to reduce server load by combining queries into joins (including an email alert cron job that typically inv

9条回答
  •  误落风尘
    2020-12-08 02:41

    I ended up just building the field set for the query, as as of 2020 this still isn't supported.

    But, being a lazy programmer, I obviously didn't want to manually type this all out for all of the tables in my query. So I wrote a query to build the select statement:

    SELECT
        CONCAT(table_name, ".", column_name, " AS ", CHAR(34), table_name, ".", column_name, CHAR(34)) field_names
    FROM
        information_schema.columns
    WHERE
        table_schema = "my_database"
        AND table_name IN(
            "table_1",
            "table_2"
        );
    

    which will output something like:

    | field_names                        |
    |------------------------------------|
    | table_1.id AS "table_1.id"         |
    | table_1.name AS "table_1.name"     |
    | table_2.id AS "table_2.id"         |
    | table_2.number AS "table_2.number" |
    

    That can then easily be copied into your SELECT statement.

提交回复
热议问题