2

I am writing a flexible search mechanism for a customer's website. I am utilizing union clauses to query a number of different fields in the database in search of a string value entered by the user. This works fine except for one issue.

When comparing a string of a text to an integer that is currently set to zero, the match always returns true. In other words, according to MySQL, "email@example.com" is equal to 0.

I have tried utilizing the CAST and CONVERT function to turn this into a standard string to string comparison, but I can't seem to get the syntax right. My attempts either repeat the above issue or return no rows at all when some should match. I am also concerned that doing this would have an effect on performance since I am combining lots of unions.

What I really need is a strict comparison between an entered string and the value in the database, be it an integer or string.

EDIT: Here is an example.

CREATE  TABLE `test_table` (
`id` INT NOT NULL AUTO_INCREMENT ,
`email` VARCHAR(255) NOT NULL ,
`phone` BIGINT(19) NOT NULL DEFAULT '0' ,
PRIMARY KEY (`id`) )
ENGINE = MyISAM;

INSERT INTO `test_table` (`id`, `email`, `phone`) VALUES (1, 'email@example.com', 0);

SELECT * FROM test_table WHERE phone = 'email@example.com';

Execute this and the one row that has been inserted will return. My issue is that it shouldn't!

4

2 回答 2

1

此查询应该失败:

SELECT * FROM test_table WHERE cast(phone as char) = 'email@example.com';

原来问题的原因是在比较字符串和数字的时候,把字符串转换成数字(所以可以写where phone = '123')。您需要使用该字段的显式转换使其成为字符串到字符串的比较,以防止这种默认转换。

不幸的是,像这样的强制转换可能会阻止它使用索引。即使该字段已经是char,强制转换显然会阻止它建立索引。

您也可以在输入验证期间解决它:如果phone是整数,则不允许用户在搜索字段中提供非整数值。

于 2013-05-20T16:54:14.813 回答
-1

怎么换:

SELECT * FROM test_table WHERE phone = 'email@example.com'

和:

SELECT * FROM test_table WHERE phone = 'email@example.com' and phone <> 0

<> 表示不同。

这对您有用,因为您在电话列中使用 0 表示没有电话号码(尽管使用 NULL 表示没有电话号码会更好)。

于 2013-05-20T16:54:08.360 回答