2

伙计们,

我有两张桌子:

表格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)并仅列出第一个表中的记录,这些记录(例如)在第二个表中有 PARAM=10 和 PARAM=20。这样,对于此示例,查询应返回:

UID      NAME
1        Name1
3        Name3

..因为只有 Name1 AND Name3 有 BOTH PARAM=10 AND PARAM=20

我怎样才能做到这一点?我知道这可能很简单,但我找不到答案,也找不到这里,谷歌也找不到。

先感谢您!内德

4

5 回答 5

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

于 2012-08-29T10:01:31.140 回答
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;
于 2012-08-29T10:00:36.260 回答
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
于 2012-08-29T10:04:04.930 回答
0

您不必加入:

SELECT * FROM TABLE1 WHERE IN (SELECT UID FROM TABLE2 WHERE PARAM IN (10, 20) )

于 2012-08-29T10:03:25.367 回答
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);
于 2012-08-29T10:03:26.690 回答