Wildcards in column name for MySQL

后端 未结 4 975
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2020-12-09 20:42

    No, you cannot dynamically produce the list of columns to be selected. It will have to be hardcoded in your final query.

    Your current query would produce a result set with one column and the value of that column would be the string "word%" in all rows that satisfy the condition.

    0 讨论(0)
  • 2020-12-09 20:44

    You can generate the list of column names first by using

    SHOW COLUMNS IN tblname LIKE "word%"
    

    Then loop through the cursor and generate SQL statement uses all the columns from the query above.

    "SELECT {0} FROM searchterms WHERE onstate = 1".format(', '.join(columns))
    
    0 讨论(0)
  • 2020-12-09 20:51

    This could be helpful: MySQL wildcard in select

    In conclusion it is not possible in MySQL directly.

    What you could do as a dirty workaround is get all the column names from the table with an initial query (http://dev.mysql.com/doc/refman/5.0/en/show-columns.html) and then compare in python if the name matches your pattern. Afterwards you could do the MySQL select statement with the found column names like this:

    SELECT word1, word2, word3 from searchterms where onstate = 1;
    
    0 讨论(0)
提交回复
热议问题