SQL JOIN 3表所有查询组合

时间:2015-04-15 18:00:03

标签: mysql sql select join

VENN DIAGRAM http://hom.wdfiles.com/local--files/the-logic-diagrams-of-john-venn/Venn3.PNG

Table_A(PK,VALUE)

  • | 1 |福克斯|
  • | 2 | COP |
  • | 3 | TAXI |
  • | 4 | LINCOLN |
  • | 5 | ARIZONA |
  • | 6 |华盛顿|
  • | 7 |戴尔|
  • | 10 | LUCENT |

表_(PK,VALUE)

  • | 1 | TROT |
  • | 2 | CAR |
  • | 3 | CAB |
  • | 6 |纪念碑|
  • | 7 | PC |
  • | 8 | MICROSOFT |
  • | 9 | APPLE |
  • | 11 | SCOTCH |

Table_C(PK,VALUE)

  • | 1 | UP |
  • | 3 |对|
  • | 7 | LEFT |
  • | 10 | EAST |
  • | 11 | WEST |
  • | 14 | DOWN |
  • | 20 | NORTH |
  • | 21 |南|

为了获得显示的VENN图中的每个区域,需要编写哪些MySQL JOIN查询:

因此,每个区域的输出应显示每个表中匹配的键值对。检查下面的7以了解运行查询后应显示的内容。

1 => 4,5

2 => 8,9

3 => 2,6

4 => 14,20,21

5 => 10

6 => 11

7 =&gt; 1,3,7为{(1,FOX; 1,TROT; 1,UP),(3​​,TAXI; 3,CAB; 3,RIGHT),(7,DELL; 7,PC; 7,LEFT)} < / p>

1 个答案:

答案 0 :(得分:0)

/ * 1 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_a A LEFT JOIN table_b B on B.PK = A.PK LEFT JOIN table_c C on C.PK = A.PK其中B.PK为NULL且C.PK为NULL;

/ * 2 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_b B LEFT JOIN table_a A on B.PK = A.PK LEFT JOIN table_c C on C.PK = B.PK其中C.PK为NULL且A.PK为NULL;

/ * 3 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_a A INNER JOIN table_b B on A.PK = B.PK LEFT JOIN table_c C on A.PK = C.PK,其中A.PK = B.PK和C.PK为NULL;

/ * 4 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_c C LEFT JOIN table_a A on C.PK = A.PK LEFT JOIN table_b B on C.PK = B.PK其中A.PK为NULL且B.PK为NULL;

/ * 5 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_a A LEFT JOIN table_b B on A.PK = B.PK INNER JOIN table_c C on A.PK = C.PK,其中A.PK = C.PK和B.PK为NULL;

/ * 6 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_b B LEFT JOIN table_a A on A.PK = B.PK INNER JOIN table_c C on B.PK = C.PK,其中B.PK = C.PK和A.PK为NULL;

/ * 7 * /

选择A.PK为A_PK,A.Value为A_Value,B.PK为B_PK,B.Value为B_Value,C.PK为C_PK,C.Value为C_Value from table_a A INNER JOIN table_b B on A.PK = B.PK INNER JOIN table_c C on A.PK = C.PK;

现在我想知道是否可以通过将JOIN条款保持为INNER JOIN并且不混合LEFT或RIGHT JOINS来完成这项工作,但我不想再次因为发布问题而投票。