我需要在代码的特定区域锁定一个表。
所以我锁定了我的桌子:
LOCK TABLE christmas_game WRITE;
工作正常。
现在我需要在这张桌子上SELECT
,所以我这样做:
SELECT SQL_NO_CACHE prize
FROM christmas_game
WHERE user_id = {$this->user_id}
ORDER BY created_at DESC
LIMIT 2
哪个也好。但由于某种原因,这根本不起作用:
SELECT prize
FROM christmas_game
WHERE DATE(created_at) = CURDATE()
AND user_id != '{$uniqId}'
GROUP BY prize
UNION
SELECT prize
FROM christmas_game
WHERE user_id = {$user->user_id}
AND user_id != '{$uniqId}'
AND prize IN ('promo_1', 'promo_2')
我收到错误消息:Table 'christmas_game' was not locked with LOCK TABLES
。
显然UNION
在这里有问题,因为没有它,两个查询都可以正常工作。
为什么?
答案 0 :(得分:2)
您必须锁定两个表,并且不能锁定相同表的两次。
解决方案是为表添加别名:
LOCK TABLE christmas_game as table_locked_game_1 WRITE, christmas_game as table_locked_game_2 write;
然后在您的联盟中添加相同的别名:
SELECT prize
FROM christmas_game as table_locked_game_1
WHERE DATE(created_at) = CURDATE() GROUP BY prize
UNION
SELECT prize FROM christmas_game as table_locked_game_2
WHERE user_id = 81
AND prize IN ('promo_1', 'promo_2')