mysql 3表连接更新

时间:2012-03-29 20:04:55

标签: mysql join left-join

我正在尝试通过检查两个连接的表来更新列的状态。即使我没有收到错误。列不更新。我想获取一般的blockplot id,看看是否有匹配的事务和/或容器。如果有交易但没有容器,我需要将其标记为P。

UPDATE (general
LEFT JOIN 
transactions 
ON 
general.blockplotid=transactions.blockplotid)
LEFT JOIN 
container 
ON 
general.blockplotid=container.blockplotid
SET general.lotstatus = 'P'
WHERE general.lotstatus != 'U' AND
transactions.id_transaction IS NOT NULL AND
container.id_container IS NULL

总结一下,我有3张桌子。我只想在一个表中更新一个列。我想检查其他两个表中的值,它们的值取决于设置值。这三个表与外键的主键相连。

当我执行双连接选择语句时。查询似乎是正确的。

SELECT transactions.blockplotid AS blockplotid_2, container.blockplotid AS blockplotid_1, general.blockplotid, general.lotstatus, container.id_container, transactions.id_transaction
FROM ((general LEFT JOIN transactions ON general.blockplotid=transactions.blockplotid) LEFT JOIN container ON general.blockplotid=container.blockplotid)
ORDER BY general.blockplotid ASC

然而,似乎更新的连接不像select。

此查询似乎有效:

此查询有效:

UPDATE ((general LEFT JOIN transactions ON transactions.blockplotid=general.blockplotid) LEFT JOIN container ON container.blockplotid=general.blockplotid)
SET general.lotstatus='P'
WHERE general.blockplotid!='U'  AND container.id_container is null  AND transactions.id_transaction is not null 

这里的区别是IS NOT NULL的情况以及where条件的顺序。 对此有任何解释吗?

2 个答案:

答案 0 :(得分:2)

我怀疑连接的括号/位置。尝试这样的设置:

UPDATE

Table1

SET

Table1

. Field1 = StagingTable . Field1

FROM

Table1

INNER JOIN StagingTable
ON Table1 . Field2 = StagingTable . Field2
WHERE

StagingTable . Field3 IS NOT NULL 

答案 1 :(得分:0)

我建议重构你的UPDATE语句以拥有一个嵌入式SUB-SELECT。更新一般设置lotstatus =(SELECT .... WHERE ....)