Wildcards in column name for MySQL

后端 未结 4 989
情话喂你
情话喂你 2020-12-09 19:58

I am trying to select multiple columns, but not all of the columns, from the database. All of the columns I want to select are going to start with \"word\".

So in ps

4条回答
  •  悲哀的现实
    2020-12-09 20:40

    No, SQL doesn't provide you with any syntax to do such a select.

    What you can do is ask MySQL for a list of column names first, then generate the SQL query from that information.

    SELECT column_name
    FROM information_schema.columns
    WHERE table_name = 'your_table'
        AND column_name LIKE 'word%'
    

    let's you select the column names. Then you can do, in Python:

    "SELECT * FROM your_table WHERE " + ' '.join(['%s = 1' % name for name in columns])
    

    Instead of using string concatenation, I would recommend using SQLAlchemy instead to do the SQL generating for you.

    However, if all you are doing is limit the number of columns there is no need to do a dynamic query like this at all. The hard work for the database is selecting the rows; it makes little difference to send you 5 columns out of 10, or all 10.

    In that case just use a "SELECT * FROM ..." and use Python to pick out the columns from the result set.

提交回复
热议问题