将子查询中的值提取到主查询

时间:2013-08-14 11:57:13

标签: sql

我很难从子查询中提取值。

假设我有以下表格:

D(fid,pid,r),

F(fid,t,j)

我需要在第一次选择时从下面的子查询中获取f.j.

SELECT pid -- Here I need f.j to show up
FROM D
WHERE r='something' AND fid IN
            (
            SELECT f2.fid
            FROM F f2, 
                (
                SELECT f.j, COUNT(*) -- I need f.j above
                FROM F f
                GROUP BY f.j
                HAVING COUNT(*) >=2
                ) f
            WHERE f.j = f2.j
            )
GROUP BY pid
HAVING COUNT(*) >= 2

感谢。

4 个答案:

答案 0 :(得分:0)

我会以这种形式创建临时表 T(pid,j)。然后你可以分别插入所有的pid和f.j数据。

答案 1 :(得分:0)

SELECT d.pid, f.j, count(f.*) as count
FROM d inner join f
on d.fid = p.fid
WHERE d.r = "something"
GROUP by d.pid, f.j
HAVING count(f.*) >=- 2

请注意,我没有尝试过此查询。但是,我想这应该是如何看待的。

答案 2 :(得分:0)

由于没有样本数据,因此不清楚输出应该是什么,您仍然可以尝试以下操作,但这不是优化的。

SELECT  pid ,
        t.j -- Here I need f.j to show up
FROM    D
        INNER JOIN ( SELECT f2.fid ,
                            f2.j
                     FROM   F f2 ,
                            ( SELECT    f.j 
                              FROM      F f
                              GROUP BY  f.j
                              HAVING    COUNT(*) >= 2
                            ) f
                     WHERE  f.j = f2.j
                   ) t ON D.fid = t.fid
WHERE   r = 'something'
GROUP BY pid, t.j
HAVING  COUNT(*) >= 2

答案 3 :(得分:0)

可能是这样的:

SELECT D.pid, E.j
FROM D
INNER JOIN (SELECT f1.j
        FROM F f2
        INNER JOIN 
            (
            SELECT f.j, COUNT(*)
            FROM F f
            GROUP BY f.j
            HAVING COUNT(*) >=2
            ) f1
        ON f1.j = f2.j
       ) E
 ON D.fid = E.fid
 WHERE r='something' AND fid IN
        (
        SELECT f2.fid
        FROM F f2, 
            (
            SELECT f.j, COUNT(*) -- I need f.j above
            FROM F f
            GROUP BY f.j
            HAVING COUNT(*) >=2
            ) f
        WHERE f.j = f2.j
        )
 GROUP BY D.pid
 HAVING COUNT(*) >= 2