当前位置:网站首页>MySQL performs an inner join on query. The query result is incorrect because the associated fields have different field types.

MySQL performs an inner join on query. The query result is incorrect because the associated fields have different field types.

2022-06-13 05:38:00 Flying it people

today, The test students reported that there was a problem with XX's query function , The unconfigured data is still found , Look through the code , Extract queried sql, Query the client to find whether there is any associated data or not , After checking for a long time, I found that , It is caused by mismatching of associated field types .

Solution : Use mysql Of cast function , For example, the modification in the following picture can be solved .

OK, I know the solution , Explain the reason and the scenario , It is convenient for students to analyze their own situation .

First create 2 A watch :

The place I enclose will be related to a fruit table

this 2 The enclosed parts of a table are used for association query , You can see that one is int(11)   One is varchar(64)   type ,2 What happens when two different types of associations are made ? Let's go on to explain .

Enumerate 2 Data of tables :

goods surface :

orange surface :

 

See the data of the two tables , Next I need goods Tabular id Fields and orange Tabular goods_type Fields are associated , Students who understand should be able to know , Theoretically, the data found after correlation must look like the following :

But after we implemented , Below sql What data is generated after the statement ?

sql The statement is as follows :

select g.name as goods_name ,o.goods_type,o.name
from goods g inner join orange o on g.id = o.goods_type
where g.type = 1

The queried data are as follows :

EH ? I found one goods_type yes 1ad...( It's small anyway T Fabricate ), This shouldn't be . Yes , I met this at first bug That's what I thought when I was , Later, many people inquired about it ,mysql When associating different types of fields , The field will be converted to the same type for comparison , This may lead to such uncorrelated data .

therefore , Students who encounter the above problems , Refer to the situation mentioned at the beginning of this post to solve .

But remember , When doing table Association , The associated fields must be the same , Because if you do large data linked table query , This is because the query efficiency is reduced due to linked tables , If the field types are different , And it also causes mysql The conversion type comparison will be carried out continuously , In this case , It may reduce the query efficiency , Infinite heap of slow queries sql But it will cause problems for the whole system .

原网站

版权声明
本文为[Flying it people]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280509014419.html