Any way to select from MySQL table where a field ends in certain character/number?

后端 未结 7 536
南方客
南方客 2020-12-21 10:57

I am hoping to run a mysql_query where I can select a row if a certain field ends in a number. For example:



        
7条回答
  •  盖世英雄少女心
    2020-12-21 11:40

    You could do it with a cast and LIKE, but the performance is likely to be terrible for any non-trivial amount of data (I've not tested in your particular case, but in my experience, casting to string so you can use string operations really slows a query down).

    A better way would be to use modulus.

    For example, to get all the rows where the numerical field ends in a 4:

    SELECT *
    FROM table
    WHERE MOD(column_of_interest, 10) = 4
    

    Again, I've not benchmarked this, but it's probably going to perform better than casting would.

    Of course, if the column type is already a string, then LIKE is the way to go, as using MOD on strings would also require a cast.

提交回复
热议问题