2012-12-18 241 views
0

我有两个mysql表:a。 myTable1和b。 myTable2从另一个查询的结果查询第二个mysql表

首先,我需要查询第一个表(myTable1)以获取'custid'和'age',然后查询第二个表(myTable2)以获取与中间结果中的任何记录匹配的所有记录。

第一个查询的结果看起来像如下:

其中的itemid在(2762,2763)

custid  age 
"8897953" 53.1839 
"1433515" 49.5507 
"7638023" 59.4099 
"2310899" 46.8374 
"6736604" 47.3001 

选择不同的客户ID,从mtyTable1现在的年龄,如何写一个有效的嵌套查询搜索“myTable2”查找所有记录?

回答

1

尝试:

SELECT DISTINCT t2.* 
FROM mtyTable1 t1 INNER JOIN Table2 t2 ON t1.custid=t2.custid AND t1.age=t2.age 
WHERE t1.itemid IN (2762 , 2763) 
+0

谢谢。为我工作,但有点慢。 – learner

2

JOIN两个表:

SELECT t1.* 
FROM yourTable2 t1 
INNER JOIN 
(
    select distinct custid,age 
    from mtyTable1 where itemid in (2762 , 2763) 
) t2 ON t1.custid = t2.custid AND t1.age = t2.age 

或者:

SELECT t1.* 
FROM yourTable2 t1 
INNER JOIN yourTable1 t2 ON t1.custid = t2.custid AND t1.age = t2.age 
WHERE t2.itemid in (2762 , 2763) 
相关问题