我需要一些帮助来构建 SQL 查询(在 MySQL 中)。我有两张 table 。表 1 和表 2 位于不同的数据库主机/架构上。
表1有custid、标签、prod1id、prod2id、prod3id 表2有custid、prodid
现在的查询是更新Table1的tag字段。如果表2中也存在某个客户的prod1id、prod2id、prod3id条目,则该字段需要为1。这是一个例子
表1
custid, tag, prod1id, prod2id, prod3id
1 1 12 13 14
2 0 24 25 26
表2
custid, prodid
1 12
1 13
1 14
2 24
2 26
客户 #2 的标签字段为 0,因为表 2 中不存在 prod2id(25)。 有人可以帮助我形成查询吗?
最佳答案
这样的东西应该可以工作(我面前没有 MySQL),所以 case 语句可能需要一些工作
UPDATE
Table1
SET
tag = Case
WHEN t2p1.custid IS NOT NULL
and t2p2.custID IS NOT NULL
and t2p3.custId IS NOT NULL then 1
ELSE 0
END
FROM
table1 t1
LEFT JOIN Table2 t2p1
on t1.custid = t2p1.custid
and t1.prod1id = t2p1.prodid
LEFT JOIN Table2 t2p2
on t1.custid = t2p2.custid
and t1.prod2id = t2p2.prodid
LEFTJOIN Table2 t2p3
on t1.custid = t2p3.custid
and t1.prod3id = t2p3.prodid
关于sql - 帮助形成 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4831518/