Hyphens in column names in MySQL DB

前端 未结 6 520
無奈伤痛
無奈伤痛 2020-11-27 08:06

May be this question has been answered before but I couldn\'t find it.

I am using a 2/3 yr old MySQL database which has hyphens in its column names. When I try to us

相关标签:
6条回答
  • 2020-11-27 08:11

    Hyphens in database names aren't good also. But you can use them with the backtick trick `

    `name-with-hyphen`
    
    0 讨论(0)
  • 2020-11-27 08:18

    It's better to not use hyphens in your column names. I suffered a big problem with JOIN statements where hyphens caused big trouble - there even escaping names in back ticks didn't work.

    Convert the column names to use underscores - this is the safest way to go.

    As an alternative - in case where even backticks should cause problems (you know it happend to me) and you want to stick to hypens no matter what - just create a VIEW to reflect the same table with all the fields and query the view instead of the original table.

    0 讨论(0)
  • 2020-11-27 08:25

    I had to create a db named pre-ca_db.

    I solved the problem with

    create database `pre-ca_db`;
    

    Good luck!

    0 讨论(0)
  • 2020-11-27 08:30

    This entry at the MySQL forum suggests that you might have a problem. However, I think it's referring to data and not column names.

    This says "don't do it." Don't know how authoritative it is.

    0 讨论(0)
  • 2020-11-27 08:35

    enclose the names within `back-ticks`

    0 讨论(0)
  • 2020-11-27 08:35

    Do you have hyphens (-) or underscores (_) in your column names?

    Hyphens are a big problem because if you end up mapping a column name to a variable, most languages do not like to have hyphens inside variable names. Perhaps you are using one of the Java libraries that automatically generates variables or objects whose names are based on column names.

    Depending on the nature of your problem, there are a couple of different approaches you can use:

    1. Rename all of your columns using ALTER TABLE. Be conscious that this could affect referential integrity or other applications that depend on the database. If you don't know what that means, don't do it.
    2. Create SQL views that simple restate the tables you need but with "better" column names. This is not very efficient, but it will allow you to get what you want.
    3. Use the AS keyword when running your SELECT statements to rename columns within queries.

    None of these are great solutions, but they should get you started. Good luck!

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