Strange behavior querying an Int field with a String in MySQL

codemonkey

Using MySQL 5.5.60.

I'm running into some peculiar behavior when running select queries in Mysql. I have a table list whose schema looks like this:

+-----------------------+--------------+------+-----+-----------------+----------------+
| Field                 | Type         | Null | Key | Default         | Extra          |
+-----------------------+--------------+------+-----+-----------------+----------------+
| list_id               | int(11)      | NO   | PRI | NULL            | auto_increment |
| vendor_id             | int(11)      | NO   | MUL | NULL            |                |
| referrer_id           | int(11)      | NO   |     | 0               |                |
...

If I run this query

mysql> select * from list where list_id = "1946"\G

Everything works as it should and the list with id 1946 is returned. Here is where it gets weird. If I change my query to look like this:

mysql> select * from list where list_id = "1946dhkdf"\G  

It still returns list 1946! Clearly MySQL somehow cast off the dhkdf part and uses the 1946 portion only. So does it try to cast that value to an Integer that way? Why then does this query return and empty set?

mysql> select * from list where list_id = "xq1946dhkdf"\G 

I can't seem to find any documentation explaining this behavior. Can someone shed some light on it?

Tim Biegeleisen

You are seeing MySQL's somewhat complex casting rules at work here. When trying to compare an integer column against a string literal, either one has to be cast to integer, or the other to string. In this case, MySQL will try to cast the string literal to an integer, to match the type of the column. But, in this case, it can't cast the entire string literal to an integer, since it contains characters. Therefore, the casting rules kick in, which state that if the first N characters of the string be numeric, then use only that leading number. So, as a result the following query:

select * from list where list_id = "1946dhkdf";

will return the same result set as:

select * from list where list_id = "1946";

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    How to click an array of links in puppeteer?

  6. 6

    Merging legends in plotly subplot

  7. 7

    ViewPager2 мигает / перезагружается при смахивании

  8. 8

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  9. 9

    How to normalize different curves drawn with geom = "step" when using stat_summary

  10. 10

    无法通过Vue在传单中加载pixiOverlay

  11. 11

    как я могу удалить vue cli 2?

  12. 12

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  13. 13

    SQL Вычтите две строки друг от друга в одном столбце, чтобы получить результат

  14. 14

    Elasticsearch - Нечеткий поиск не дает предложения

  15. 15

    Single legend for Plotly subplot for line plots created from two data frames in R

  16. 16

    Описание моего типа Parser как серии преобразователей монад

  17. 17

    Как изменить цвета запятых и скобок в VS Code

  18. 18

    Сброс значения <input type = "time"> в Firefox

  19. 19

    Почему прокси в vue.config.js 404

  20. 20

    Как установить параметр -noverify с gradle ktx для робоэлектрических тестов Android?

  21. 21

    В чем разница между ifstream, ofstream и fstream?

популярныйтег

файл