2012-10-15 205 views
3

我現在不很瞭解SQL查詢,我有一個問題添加一個SQL查詢的結果的另一個查詢

SELECT PERSON_REF 
FROM IMAGES 
WHERE PERSON_REF IN (SELECT _PERSON_ID 
         FROM PERSONS 
         WHERE REGION_REF = (SELECT _REGION_ID 
              FROM REGIONS 
              WHERE REGION_ABB = "EU")) 
GROUP BY PERSON_REF 
HAVING Count(PERSON_REF) >= 3 

此查詢給我的結果一樣

2 
4 
5 
6 

現在我想使用該結果在其他查詢,如何做到這一點,我需要創建循環或有任何其他方式

SELECT PERSON_REF 
FROM IMAGES 
WHERE EFFECT_REF = 2 
     AND PERSON_REF IN (2, 4, 5, 6) 
+0

你不能在開發代碼中做到這一點,或者你必須使用SQL嗎?你有沒有在MySQL的功能? –

+0

好的,但如何在SQL中做到這一點 –

回答

1

試試這個:

select Person_Ref from Images where Effect_Ref = 2 and Person_Ref IN 
(your first query which gives 2 4 5 6) 
1
select Person_Ref from Images where Person_Ref IN ( 
Select _Person_ID from Persons where 
Region_Ref in (select _Region_ID from Regions where Region_Abb = "EU")) 
and EFFECT_REF = 2 
group by Person_Ref HAVING COUNT(Person_Ref) >= 3 
1

試試這個:

SELECT PERSON_REF 
FROM IMAGES 
WHERE EFFECT_REF = 2 
     AND PERSON_REF IN (SELECT PERSON_REF 
          FROM IMAGES 
          WHERE PERSON_REF IN (SELECT _PERSON_ID 
               FROM PERSONS 
               WHERE 
           REGION_REF = (SELECT _REGION_ID 
               FROM REGIONS 
               WHERE 
           REGION_ABB = "EU")) 
          GROUP BY PERSON_REF 
          HAVING Count(PERSON_REF) >= 3) 
1

JOIN三個表ImagesPersonsRegions代替這些IN S和子查詢:

SELECT i.Person_Ref 
FROM Images i 
INNER JOIN Persons p ON i.Person_Ref = p.Person_Ref 
INNER JOIN Regions r ON p.Region_Ref = r.Region_Ref 
WHERE r.Region_Abb = "EU" 
    AND i.Effect_Ref = 2 
GROUP BY i.Person_Ref 
HAVING COUNT(i.Person_Ref) >= 3 
0

有幾種方法你可以做到這一點。 您可以像使用IN示例一樣使用IN示例,但只有當您只需要一列時才能正常工作(我知道這是您的情況,但如果您遇到需要更多信息的情況,這oncolumn)

的simples將包裹查詢到parentesys,並給它一個別名,所以你可以使用它一樣,如果它是一個表:

(SELECT PERSON_REF 
FROM IMAGES 
WHERE PERSON_REF IN (SELECT _PERSON_ID 
         FROM PERSONS 
         WHERE REGION_REF = (SELECT _REGION_ID 
              FROM REGIONS 
              WHERE REGION_ABB = "EU")) 
GROUP BY PERSON_REF 
HAVING Count(PERSON_REF) >= 3) MY_ALIAS 

然後喲天亞社與其他查詢加盟。但這通常不是一個好方法。

最好apporach,其使用通用表表達式(CTE的),所以你會做這樣的事情:

with MY_FIRST_QUERY as(
SELECT PERSON_REF 
    FROM IMAGES 
    WHERE PERSON_REF IN (SELECT _PERSON_ID 
          FROM PERSONS 
          WHERE REGION_REF = (SELECT _REGION_ID 
               FROM REGIONS 
               WHERE REGION_ABB = "EU")) 
    GROUP BY PERSON_REF 
    HAVING Count(PERSON_REF) >= 3 
) 
select MY_FIRST_QUERY.PERSON_REF 

和你加入它問心無愧任何你需要

0

只需添加並向第一個謂詞並指定另一個謂詞。

SELECT PERSON_REF FROM IMAGES WHERE PERSON_REF IN(SELECT _PERSON_ID 向個人 WHERE REGION_REF =(SELECT _REGION_ID FROM REGIONS WHERE REGION_ABB = 「EU」)) AND EFFECT_REF = 2 GROUP BY PERSON_REF HAVING Count(PERSON_REF)> = 3

相關問題