2017-03-01 117 views
-1

我有一個表的樣子:SQL簡單的請求

ID | Advert_id | Iso_code 
----|------------|----------- 
1 | 22   | en_US 
2 | 22   | de_DE 
3 | 11   | zh_CE 
4 | 11   | nl_NL 

我需要返回ID,比如我有Advert_ID = 22ID 1和2 iso_code = en_USde_DE但如果Advert_IDiso_code = en_US回報只有id = 1如果不回所有ID(Advert_ID = 11不已iso_code = en_US所以返回Id 3和4)

+0

你用什麼類型的數據庫? – DVT

+0

對不起,sql-server – k0le

+0

所以,也許你想'從表中選擇id where Advert_ID = 22和iso_code ='en_US''? – chris85

回答

0

從您的評論:

,我需要選擇所有 「Advarte_ID」,檢查iso_code如果=「EN_US」迴歸只有'en_US'的ID。

如果我理解你檸好,這將有助於:

SELECT ID 
FROM YourTablName 
WHERE iso_code = 'en_US'; 

這將只返回Advert_ID S的有`iso_code = 'EN_US'。

更新:

IF EXISTS (SELECT * FROM YourTable WHERE iso_code = 'en_US') 
BEGIN 
SELECT ID 
FROM YourTablName 
WHERE iso_code = 'en_US'; 
END 
    ELSE 
    BEGIN 
     SELECT ID 
     FROM YourTable; 
    END 
+0

好吧,但我需要返回也是ID,其中iso_code是不相等'en_US' – k0le

+0

因此,選擇所有ID,在你說的評論**返回只有ID與en_US'** – Sami

+0

如果iso_code有en_US返回https:/ /scr.hu/P1B54o如果沒有返回https://scr.hu/LrV5vo //我需要選擇所有「Advarte_ID」並檢查iso_code if ='en_US「只返回ID與'en_US'但是如果iso_code沒有en_US返回它擁有的所有ID – k0le

0

使用or not exists()

select * 
from t 
where (t.iso_code = 'en_US' 
    or not exists (
     select 1 
     from t as i 
     where t.Advert_id = i.Advert_id 
      and i.iso_code = 'en_US') 
    ) 

測試設置:http://rextester.com/SGH43248

回報:

+----+-----------+----------+ 
| id | advert_id | iso_code | 
+----+-----------+----------+ 
| 1 |  22 | en_US | 
| 3 |  11 | zh_CE | 
| 4 |  11 | nl_NL | 
+----+-----------+----------+  
+0

不完全,但它可以幫助我 – k0le