0

我试图让结果表包含其中的行

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
4

2 回答 2

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;

另请参阅这个简短的演示

于 2013-10-16T10:20:50.257 回答
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
于 2013-10-16T07:22:56.497 回答