帮助形成SQL查询

时间:2011-01-28 18:02:56

标签: sql mysql database

我需要一些帮助来构建SQL查询(在MySQL中)。我有两张桌子。表1和表2位于不同的db主机/架构上。

Table1有custid,tag,prod1id,prod2id,prod3id 表2有custid,prodid

现在查询是更新Table1的标记字段。如果某个客户的表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中不存在25的prod2id。 有人可以帮我形成查询吗?

3 个答案:

答案 0 :(得分:1)

这样的事情应该有效(我没有MySQL在我面前)所以案例陈述可能需要一些工作

 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

答案 1 :(得分:0)

这应该有效:

UPDATE Table1 t1
    SET tag=1 
    WHERE EXISTS(SELECT 1 FROM Table2 t2 WHERE t2.custId = t1.custId AND t2.prodId = t1.prod1Id)
    AND EXISTS(SELECT 1 FROM Table2 t2 WHERE t2.custId = t1.custId AND t2.prodId = t1.prod2Id)
    AND EXISTS(SELECT 1 FROM Table2 t2 WHERE t2.custId = t1.custId AND t2.prodId = t1.prod3Id)

答案 2 :(得分:0)

以下是我们不必为每个prodid做join(或exists)的方法:

UPDATE table1, (SELECT table1.custid, (COUNT(*) = 3) AS tag
                  FROM table1 JOIN table2 ON table1.custid = table2.custid
                 WHERE table2.prodid IN (table1.prod1id, table1.prod2id, table1.prod3id)
              GROUP BY table1.custid) newtags
SET table1.tag = newtags.tag
WHERE table1.custid = newtags.custid;