How do you avoid column name conflicts?

前端 未结 8 1146
挽巷
挽巷 2021-01-05 12:35

I was recently assigned a task of creating an auction system. During my work, I met numerous occasions where my SQL queries that contained joins failed to execute due to amb

相关标签:
8条回答
  • 2021-01-05 13:00

    The golden rule of thumb is that if you are ever using more than one table at all, alias the tables, and explicitly alias all columns.

    This consistency will get you deep into the force, young padawan.

    0 讨论(0)
  • 2021-01-05 13:06

    My experience is that that the benefits of the extra keystrokes outweighs the short time it takes to type them by far in the long run, at latest when you need to look at a query that you have written a year ago or so.

    0 讨论(0)
  • 2021-01-05 13:12

    Your approach is correct, but you can also provide an alias for your table:

    SELECT a.* FROM TableA A
    

    in here you can refer to TableA as simply A.

    0 讨论(0)
  • 2021-01-05 13:20

    I've faced with MySQLSyntaxErrorException:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'rank

    after executing the following query:

    insert into my_table (rank) values (1);

    Because rank column name clashes with sql keyword rank.

    SOLUTION:

    I've added back quotes to rank column name and problem was solved:

    insert into my_table (`rank`) values (1);

    Another way to solve the problem is to use table name instead of back quotes:

    insert into my_table (my_table.rank) values (1);

    0 讨论(0)
  • 2021-01-05 13:21

    You need to use AS alias.

    You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.

    An alias name could be anything, but usually it is short.

    0 讨论(0)
  • 2021-01-05 13:21

    Change your naming convention so that each data element has a unique name in the schema e.g. auction_id, bid_id, user_id, etc. Ideally the name of the data element will not change between tables but sometimes you will need to add a qualifier to create a synonym e.g. adding_user_id and bidding_user_id if user_id appeared twice in the same table. You should document data element names and their synonyms in a data dictionary.

    0 讨论(0)
提交回复
热议问题