Why 3 rows deleted sql query puzzle?
can anybody tell me the technical reason for this?
CREATE TABLE test (
id varchar(3) NOT NULL,
PRIMARY KEY (id)
);
INSERT IN开发者_如何学运维TO test VALUES ('0'), ('1'), ('2'), ('ab'), ('bb');
select * from test;
DELETE FROM test WHERE id=0;
Which Deletes 3 rows from table test.
Because this:
SELECT 0 = 'ab';
+----------+
| 0 = 'ab' |
+----------+
| 1 |
+----------+
To delete exact rows use BINARY operator, it will force byte by byte comparison -
DELETE FROM test WHERE id = BINARY 0;
When you compare numbers to strings, they are compared as float numbers. Any string that does NOT start with a digit is implicitly converted to number 0.
There is Difference Between a Character '0' and an integer 0.. When u Compare a Char with integer the Char string if not an integer returns a false value (i,e) A 0 hence making the condition true and delete the First, 4th and 5th row from ur Table... To Delete the particular row you need to check condition like this...
Delete from test where id = '0'; (A Char 0 not An Integer 0)
Try instead comparing values of the same type e.g.
DELETE FROM test WHERE id = CAST(0 AS VARCHAR(3));
Okay got first i confused when i see this but now i got it when you're running
select * from test;
DELETE FROM test WHERE id=0;
This query Compares every row as a Integer not string, So when MySQL comes to ab & bb so MySQL Take it as a 0 and delete it if you start it with any digit like 1ab so MySQL Take 1ab as 1 and when you fire query for deleting 1 instead of 0 it will delete 1ab
Try
select * from test;
DELETE FROM test WHERE id='0';
This Code compare rows as a string so when he get exact '0' MySQL delete it else nothing.
精彩评论