【问题标题】:SQL Join with multiple row condition in second tableSQL Join 在第二个表中具有多行条件
【发布时间】:2013-08-29 05:45:46
【问题描述】:

我有一个关于 SQL 连接的问题,它涉及第二个连接表中的多个条件。以下是表格详情

表 1

pId 状态    keyVal
----  --------  ------ 
100  1          45 
101  1          46 

表 2

pId     模式      modeVal
100     2               5
100     3               6
101     2               7
101     3               8

我有以上两个表,我正在尝试根据以下条件加入以获取 pId

keyVal = 45 和 status = 1 的 pId 与 mode = 2 和 modeVal 5 和 mode =3 和 modeVal = 6 的 table2 连接

我期望的结果是返回 pid = 100

你能帮我做一个连接查询吗?

【问题讨论】:

  • FROM table1 JOIN table2 on table1.pld = table2.pld WHERE table2.modeVal IN (5,6) AND table2.mode IN (2,3) 我猜,连接条件只有pld,在你的 where 子句中你把另一个条件放在预期的结果中
  • 它是否适用于 (mode=2 and modeValue=5) 和 (mode=3 and modeValue=6) 的特定组合?如果两个条件都满足并且成对 (2,5) 和 (3,6),则查询应返回 pId
  • 一点也不,IN操作符就像OR操作符,只需要其中一个值就可以返回结果。在你的情况下,你可以使用你提到的东西WHERE (mode=2 and modeValue=5) or (mode=3 and modeValue=6)
  • 您是要在至少这两个组合上匹配,还是完全这两个组合不匹配?
  • 但是即使表 2 中的第 2 行不存在,这也会返回 pId = 100。我希望只有在表 2 中的第 1 行和第 2 行存在(AND 条件)时才返回 100。

标签: sql join


【解决方案1】:

一种方法是使用GROUP BYHAVING来统计找到的行数为2,其中2个符合条件;

WITH cte AS (SELECT DISTINCT * FROM Table2)
SELECT t1."pId" 
FROM Table1 t1 JOIN cte t2 ON t1."pId" = t2."pId"
WHERE t1."status" = 1 AND t1."keyVal" = 45
GROUP BY t1."pId"
HAVING SUM(
  CASE WHEN t2."mode"=2 AND t2."modeVal"=5 OR t2."mode"=3 AND t2."modeVal"=6 
       THEN 1 END) = 2 AND COUNT(*)=2

如果 t2 中的值已经不同,您可以删除 cte 并直接从 Table2 中选择。

An SQLfiddle to test with.

【讨论】:

    【解决方案2】:
    SELECT columns
    FROM table1 a, table2 B
    WHERE a.pid = B.pid
        AND a.keyval = 45
        AND a.status = 1
        AND (
            (B.mode = 2 AND B.modeval = 5)
            OR 
            (B.mode = 3 AND B.modeval = 6)
        )
    

    【讨论】:

      【解决方案3】:

      下面的查询应该很适合你

      select distinct table1.pid FROM table1 JOIN table2 
      on table1.pid = table2.pid 
      WHERE table2.modeValue IN (5,6) AND table2.mode IN (2,3) AND table1.keyVal=45 and table1.status=1;
      

      【讨论】:

      • 感谢您的回答,但它适用于 (mode=2 and modeValue=5) 和 (mode=3 and modeValue=6) 的特定组合吗?
      • 你必须这样做:WHERE (table2.modeValue =6 AND table2.mode =3 AND table1.keyVal=45 and table1.status=1) 或 (table2.modeValue =5 AND table2 .mode =2 AND table1.keyVal=45 and table1.status=1);
      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2011-05-07
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多