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

后端 未结 7 420
南方客
南方客 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:35

    You can use LIKE and a wild card expression it should be somthing like

    SELECT id FROM table WHERE id REGEX '%0$'
    SELECT id FROM table WHERE id REGEX '%1$'
    

    and so on.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 11:41
    SELECT id
      FROM table
     WHERE id LIKE '%0'
    
    0 讨论(0)
  • 2020-12-21 11:41

    You can use regular expressions if you need to find if field is ending in a number or not as follows

    SELECT id FROM table WHERE id REGEXP '[0-9]$'
    

    Hope it helps...

    0 讨论(0)
  • 2020-12-21 11:53

    SELECT id FROM table WHERE mod(id, 10) = 1

    give it a go

    0 讨论(0)
  • 2020-12-21 11:54
    SELECT ...
      WHERE somefield LIKE '%1'
    
    0 讨论(0)
提交回复
热议问题