SQL一对多列关联行

时间:2015-05-14 04:34:10

标签: mysql one-to-many

根据下表,我想选择与多个'SUB_CODE'相关联的'CODE'的行。

+------+------------+-------------+
| DIV  |    CODE    |  SUB_CODE   |
+------+------------+-------------+
| 11   | 1000       | 1212        |
| 11   | 1000       | 1213        |
| 11   | 1000       | 3434        |
| 11   | 1000       | 1000        |
| 11   | 1000       | 3000        |
| 11   | 3000       | 1213        |
| 11   | 2000       | 1212        |
| 20   | 1500       | 5656        |
| 20   | 1500       | 1213        |
+------+------------+-------------+

对于上表,结果应为

+------+------------+-------------+
| DIV  |    CODE    |  SUB_CODE   |
+------+------------+-------------+
| 11   | 1000       | 1212        |
| 11   | 1000       | 1213        |
| 11   | 1000       | 3434        |
| 11   | 1000       | 1000        |
| 11   | 1000       | 3000        |
| 11   | 1500       | 5656        |
| 11   | 1500       | 1213        |
+------+------------+-------------+

这就是我尝试的,我的结果如何失败。

Select CODE from TABLE_NAME where (count(SUB_CODE) > 1);  

2 个答案:

答案 0 :(得分:1)

首先获取存在多个CODE的{​​{1}};然后使用上面的结果将表列过滤作为嵌套查询进行投影:

SUB_CODE

演示:http://sqlfiddle.com/#!9/1d91f/3/0

答案 1 :(得分:0)

尝试这个:

Select `DIV`, `CODE`, `SUB_CODE` from TABLE_NAME GROUP BY `SUB_CODE`