I want the name column to be unique here. Because other problem unique keys cannot be added, cannot use on duplicate key update.
I try use insert select, but not work.
INSERT INTO test2 (NAME, hotStatus)
SELECT 'A', 1 WHERE NOT EXISTS (SELECT 1 FROM test2 WHERE NAME = 'A' LIMIT 1);
table is:
CREATE TABLE `test2` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10),
`hotStatus` tinyint(1),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
@Test
public void testInsert() throws InterruptedException {
final int COUNT = 20;
Thread[] ta = new Thread[COUNT];
for (int i = 0; i < COUNT; i++) {
int hotStatus = i % 2;
ta[i] = new Thread(() -> getConn()
.update("INSERT INTO test2 (NAME, hotStatus) " +
"SELECT 'A', ? WHERE NOT EXISTS (SELECT 1 FROM test2 WHERE NAME = 'A' LIMIT 1);",
hotStatus));
}
for (Thread t : ta) {
t.start();
}
for (Thread t : ta) {
t.join();
}
}
The table is empty before running the test. After I run this test, there are a dozen more data in test2.
id name hotStatus
3 A 1
4 A 0
5 A 0
6 A 0
7 A 1
I try select for update, but can't lock it.
select * from test2 where name = 'A' for update;
I see other question, but not got answer