【问题标题】:querying second mysql table from the result of another query从另一个查询的结果中查询第二个 mysql 表
【发布时间】:2012-12-18 23:42:05
【问题描述】:

我有两个 mysql 表: myTable1 和 b。我的表2

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

第一次查询,结果如下:

select distinct custid,age from mtyTable1 where itemid in (2762, 2763)

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

现在,如何编写一个高效的嵌套查询来搜索“myTable2”以查找所有记录?

【问题讨论】:

    标签: mysql select nested-queries


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

      试试:

      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)
      

      【讨论】:

      • 谢谢。为我工作,但有点慢。
      猜你喜欢
      • 2015-03-16
      • 2019-05-29
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      相关资源
      最近更新 更多