人,
我有两张桌子:
表1:
UID NAME
1 Name1
2 Name2
3 Name3
表2:
UID PID PARAM
1 1 10
2 1 20
3 2 10
4 2 30
5 2 40
6 3 60
7 3 20
8 3 10
我需要加入两个表(t1.UID = t2.PID)并仅列出第一个表中的记录,这些记录在第二个表中有(例如)BOTH PARAM = 10 AND PARAM = 20。这样,对于此示例,查询应返回:
UID NAME
1 Name1
3 Name3
..因为只有Name1和Name3具有BOTH PARAM = 10 AND PARAM = 20
我该怎么做?我知道这可能很简单,但我也找不到答案,也不在谷歌。
提前谢谢! 奈德
答案 0 :(得分:3)
select a.name
from table1 a
inner join table2 b on (a.UID = b.PID)
where b.param in (10, 20)
group by a.name
having count(*) = 2
通过声明您的表table1 a
,您可以通过将表声明名称放在列a.name
答案 1 :(得分:1)
此查询应该有效:
SELECT t1.*
FROM table1 t1
INNER JOIN (SELECT PID
FROM table2
WHERE PARAM IN(10, 20)
GROUP BY PID
HAVING COUNT(*) = 2
)t2
ON t1.UID = t2.PID;
答案 2 :(得分:1)
select distinct t1.id
from table1 t1 join table2 t2 on t1.uid = t2.pid and t2.param = 10
join table2 t3 on t1.uid = t3.pid and t3.param = 20
答案 3 :(得分:0)
您无需加入:
SELECT * FROM TABLE1 在哪里( 从TABLE2中选择UID 参与的地方(10,20) )
答案 4 :(得分:0)
试试这个:
select uid,name from t1 where exists (select 1 from t2 where param = 10 and pid = t1.uid) and exists (select 1 from t2 where param = 20 and pid = t1.uid);