我有以下表格
,--------------------------------------------,
| contacts |
|------------,---------------,---------------|
| contact_id | contact_score | contact_email |
|------------|---------------|---------------|
| 1 | 53 | email1@xx.com |
| 2 | 53 | email2@xx.com |
| 3 | 4 | email3@xx.com |
'------------'---------------'---------------'
,------------------------,
| reputation_email_score |
|---------------,--------,
| email | score |
|---------------|--------|
| email1@xx.com | 3 |
| email3@xx.com | 4 |
'---------------'--------'
,----------------------,
| x_message_batch_4_pq |
|----------------------|
| prequeue_contact_id |
|----------------------|
| 1 |
| 2 |
'----------------------'
我想更新分数为53但仅在prequeue
表中的联系人的所有分数。如果它们不存在于reputation
表中,则必须更新为2分。
所以在这个例子中:
contact_score
上的 email1@xx.com
将更新为3
而contact_score
上的email2@xx.com
将更新为2
。
我该怎么做?我尝试编写CASE语句,但我正在努力从声誉表中获取值。
这是我尝试过的,但我收到了Error in query (1093): You can't specify target table 'x_message_batch_4_pq' for update in FROM clause
错误
UPDATE x_message_batch_4_pq
LEFT JOIN contacts ON prequeue_contact_id = contact_id
LEFT JOIN reputation_email_score ON contact_email = email
SET contact_contact_score =
(CASE WHEN
(SELECT COUNT(contact_id)
FROM x_message_batch_4_pq
JOIN contacts ON prequeue_contact_id = contact_id
JOIN reputation_email_score ON contact_email = email
WHERE contact_contact_score = '53') = 0
THEN '2'
ELSE (SELECT score FROM reputation_email_score WHERE email = contact_email)
END)
WHERE contact_contact_score = '53';
答案 0 :(得分:1)
您可以尝试使用JOIN这样的UPDATE语句,像这样使用LEFT JOIN
UPDATE contacts a
JOIN x_message_batch_4_pq b
ON a.contact_id = b.prequeue_contact_id
LEFT JOIN reputation_email_score c
ON a.contact_email = c.email
SET a.contact_score = CASE
WHEN c.score IS NULL THEN 2
ELSE c.score
END
WHERE a.contact_score = 53
我创建了一个演示here,请检查