我有table1:
+------+---------+
| id | name |
+------+---------+
| 1 | name1 |
| 2 | name2 |
| 3 | name3 |
| 4 | name4 |
+------+---------+
我有table2:
+------+---------+
| id | object |
+------+---------+
| 1 | 4 |
| 1 | 8 |
| 2 | 23 |
| 2 | 8 |
| 2 | 9 |
| 3 | 2 |
| 3 | 8 |
| 4 | 9 |
| 4 | 23 |
+------+---------+
我想选择name = name2,它有对象8,23,但是忽略只有objet 8或者只是对象23的其他id,结果将是:
+------+---------+
| id | name |
+------+---------+
| 2 | name2 |
+------+---------+
感谢您的帮助,掌握。
答案 0 :(得分:0)
当您想要找到一个SELF JOIN
有两个不同的值时,您可以使用id
。
SELECT *
FROM
(
SELECT a.id
FROM table2 AS a INNER JOIN table2 AS b
ON a.id = b.id
WHERE a.object = 8 AND b.object = 23
) x INNER JOIN table1 ON x.id = table1.id;
答案 1 :(得分:-1)
试试这个:
select a.id, a.name
from table1 a
where exists (select 1 from table2 c
where object = 8 and c.id = a.id)
and exists (select 1 from table2 c
where object = 23 and c.id = a.id)
答案 2 :(得分:-1)
怎么样:
SELECT DISTINCT table1.id, table1.name FROM table1, table2 WHERE table1.name = "name2" AND
table1.id = table2.id and (table2.object = 8 OR table2.object = 23);