试图用表A,B写一个查询,其中Cond1:A.pc = B.pc& Cond2 :(首选(A.sub = B.Sub)或者只满足Cond1的任何1行)

时间:2013-10-16 07:19:37

标签: sql join subquery

我试图让结果表包含行

Condition1: A.pc=B.pc AND 
Condition2: (preferred (A.sub = B.Sub)  or 
             else any one row that satisfy only Condition1)

我尝试过以下内连接查询和其他一些连接和子查询,但无法弄清楚编写具有上述奇怪条件的查询的确切方法。

SELECT * FROM tblA AS A INNER JOIN tblB AS B
ON A.sub=B.sub
WHERE A.pc=B.pc


tblA
-------------------
| id  |  pc | sub |
-------------------
| 0   | 5   | abc |
| 1   | 8   | def |
| 2   | 6   | ghi |
| 3   | 2   | jkl |
| 4   | 7   | mno |
| 5   | 19  | pqr |
-------------------

tblB
-------------------------
| pc  | sub | uml | ull |
-------------------------
| 3   |arm  |  1  |  1  |   
| 3   |gtk  |  1  |  2  |
| 3   |lmn  |  1  |  3  |
| 3   |pop  |  1  |  4  | 
| 5   |abc  |  1  |  5  |
| 5   |hlq  |  1  |  6  |
| 5   |pon  |  2  |  1  |
| 5   |qrt  |  2  |  2  | 
| 7   |alo  |  2  |  3  |
| 7   |mno  |  2  |  4  |
| 7   |ghm  |  2  |  5  |
| 7   |stm  |  2  |  6  | 
| 9   |mck  |  2  |  7  |
| 9   |plo  |  3  |  1  |
| 9   |rtk  |  3  |  2  |
| 9   |ert  |  3  |  3  |
| 6   |gji  |  3  |  4  |
| 6   |ghi  |  3  |  5  |
| 6   |yux  |  4  |  1  |
| 6   |del  |  4  |  2  |
| 2   |jkl  |  4  |  3  |
| 2   |jll  |  5  |  4  |
| 2   |uin  |  6  |  1  | 
| 2   |tro  |  6  |  2  |
| 19  |ppm  |  6  |  3  |
| 19  |kde  |  6  |  4  |
| 19  |grp  |  6  |  5  |
| 19  |sho  |  6  |  6  |
-------------------------


Expected Result Table:
-------------------------------
| id  | pc  | sub | uml | ull |
-------------------------------
| 0   | 5   |abc  |  1  |  5  |
| 2   | 6   |ghi  |  3  |  5  |
| 3   | 2   |jkl  |  4  |  3  |  
| 4   | 7   |mno  |  2  |  4  |
| 5   | 19  |ppm  |  6  |  3  | * 
-------------------------------
* notice this is a arbitrary row as (A.sub=B.sub) not found
** notice there is no result for id=1 as pc=8 do not exist in tblB

2 个答案:

答案 0 :(得分:1)

在有人提出更好的答案之前,这里有一些代码能够满足您的需求 请注意,就性能而言,这可能不是一个好的解决方案(特别是随着您的桌面增长)。

SELECT *
  FROM (
    SELECT tblA.id, tblB.* 
      FROM tblA INNER JOIN tblB 
        ON tblA.pc = tblB.pc AND 
           tblA.id NOT IN (SELECT tblA.id 
                             FROM tblA INNER JOIN tblB 
                               ON tblA.sub = tblB.sub) 
      GROUP BY tblA.id
  UNION
    SELECT tblA.id, tblB.* 
      FROM tblA INNER JOIN tblB 
        ON tblA.sub = tblB.sub 
    GROUP BY tblA.id
  ) AS tu
ORDER BY id ASC;

另请参阅此 short demo

答案 1 :(得分:0)

我想出的一种方法是在where子句中重复连接条件:

SELECT * 
FROM tblA AS A
    INNER JOIN tblB AS B 
        ON A.pc = B.pc
WHERE A.sub = B.sub 
OR A.pc = B.pc