从具有相同id的多个表中检索数据

时间:2014-07-13 17:18:12

标签: mysql sql join

我的SQL查询有问题。实际上,我想要两个表的交集。这是我的表格。

Les_Teach
+--------+-----------+
| les_id | teach_id  |
+--------+-----------+
|   10    |     1     |
|   10    |     2     |
|   10    |     3     |
|   11    |     1     |
|   11    |     6     |
+--------+-----------+

Class_Les
+--------+-----------+
| c_id   | les_id    |
+--------+-----------+
|   10    |     1     |
|   10    |     3     |
|   11    |     5     |
|   11    |     1     |
|   11    |     6     |
|   11    |     7     |
+--------+-----------+

示例1)les_id和c_id的交点为10;

Query Result 1
+--------+-----------+
|   10    |     1     |
|   10    |     3     |
+--------+-----------+

示例2)les_id和c_id的交点为11;

Query Result 2
+--------+-----------+
|   11    |     1     |
|   11    |     6     |
+--------+-----------+

SELECT DISTINCT cl.les_id 从 Class_Les cl INNER JOIN Les_Teach lt ON lt.les_id = cl.c_id WHERE lt.les_id = 10 AND cl.c_id = 10

只有Les_Teach中的les_id列和Class_Les中的c_id列,我该如何检索这样的数据?

1 个答案:

答案 0 :(得分:0)

如果您提供的示例是您想要获得的结果,则可以使用 -

表示10:

select x.*
  from les_teach x
  join class_les y
    on x.les_id = y.c_id
   and x.teach_id = y.les_id
where x.les_id = 10;

代表11:

select x.*
  from les_teach x
  join class_les y
    on x.les_id = y.c_id
   and x.teach_id = y.les_id
 where x.les_id = 11;

(省略两个表的完整交集的where子句)

测试 -

http://sqlfiddle.com/#!2/a25e87/3