MySQL SELECT查询没有选择完全匹配?

时间:2016-01-11 21:11:53

标签: mysql

SELECT DISTINCT p.id_product, t.id_tag, t.name FROM ps_tag t 
JOIN ps_product p ON p.id_product=t.name AND t.name 
IN(SELECT id_product FROM ps_product) 
AND p.available_for_order = 1 
GROUP BY t.id_tag, p.id_product
ORDER BY `p`.`id_product`  DESC

此查询返回这样的结果(在正确的结果中)

id_product  id_tag  name    
43         79020    43P109
43         79021    43P109
43         79022    43P109
43         105796   43
43         114789   43

ON语句显示p.id_product=t.name,但43不是43P109。我在哪里错了?我只需要p.id_product完全等于t.name的结果,所以只返回名称43?

2 个答案:

答案 0 :(得分:2)

就mysql而言,

42实际上等于"42Pwhatever"

mysql> select 42 = "42P123";
+---------------+
| 42 = "42P123" |
+---------------+
|             1 |
+---------------+
1 row in set, 1 warning (0.01 sec)

如果希望此比较失败,请将整数列转换为二进制字符串:

mysql> select cast(42 as binary) = "42P123";
+-------------------------------+
| cast(42 as binary) = "42P123" |
+-------------------------------+
|                             0 |
+-------------------------------+
1 row in set (0.00 sec)

原因是你的列有不同的类型,当在表达式中发生这种情况时,mysql会尝试将它们转换为公共类型(在特定情况下为整数)。因此"42P123"变为42(它会停止第一个非数字字符的转换。上面的显式转换告诉mysql将整数转换为字符串,然后比较字符串。

请在此处查看mysql转换规则:http://dev.mysql.com/doc/refman/5.7/en/type-conversion.html

答案 1 :(得分:0)

我认为是铸造问题整数与char

尝试使用

 SELECT DISTINCT p.id_product, t.id_tag, t.name 
 FROM ps_tag t 
 JOIN ps_product p ON CAST(p.id_product as char(50)) =t.name 
     AND t.name IN(SELECT id_product 
        FROM ps_product)
     AND p.available_for_order = 1 
 GROUP BY t.id_tag, p.id_product
 ORDER BY `p`.`id_product`  DESC