设置列以从另一个表复制列(在条件下)

时间:2013-07-10 08:57:58

标签: mysql sql mysqli

我目前拥有的是:

UPDATE card, records
IF(records.date_returned == null) THEN SET
card.last_seen = records.date_loaned
ELSE SET card.last_seen = records.date_returned
WHERE card.card_no = records.card_no

一点背景 - 表记录有两列 - date_loaned和date_returned,默认情况下date_returned设置为null。我想知道是否可以将temp_card中的last_seen列更改为date_returned更新时

很确定这是不可能的,但我想我正在试试运气!

-edit- *我有点希望它是自动的(例如,当记录更新时,这会触发last_seen更改)希望能够解决问题!*

-edit- 谢谢大家的回答!这是我得出的解决方案:

AFTER UPDATE ON records
FOR EACH ROW
Update card A
INNER JOIN records B
SET A.last_seen =
(CASE WHEN B.date_returned=null then B.date_loaned Else B.date_returned END )
WHERE A.card_no = B.card_no

2 个答案:

答案 0 :(得分:0)

如何使用CASE

UPDATE card, records
SET
 card= CASE records.date_returned == null 
 THEN  card.last_seen = records.date_loaned
 ELSE SET card.last_seen = records.date_returned
WHERE card.card_no = records.card_no

答案 1 :(得分:0)

你可以尝试这样..

Update  Card A INNER JOIN Record B ON (A.card_no =B.card_no) SET A.last_seen =(
                           Case WHEN B.date_returned==null
                           then B.date_loaned 
                           Else B.date_returned
                           End
                          )