SQL在第二个表中加入多行条件

时间:2013-08-29 05:45:47

标签: sql join

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

表1

pId status keyVal
---- ------- ------
100 1 45
101 1 46

表2

pId mode modeVal
100 2 5
100 3 6
101 2 7
101 3 8

我有两张桌子,我正在尝试根据以下条件加入以获得pId的

具有keyVal = 45且status = 1的pId与table2结合,其中mode2为2,modeVal为5,mode = 5,modeVal = 6

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

你可以帮我一个加入查询吗?

3 个答案:

答案 0 :(得分: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并直接从表2中选择。

An SQLfiddle to test with

答案 1 :(得分:0)

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)
    )

答案 2 :(得分:0)

以下查询应该对您有用

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;