2017-04-03 76 views
2

大家好,這是我的第一個問題,所以對我來說很簡單 - 需要一些幫助來提取一些數據。SQL新手 - 子查詢

這是兩個表我一起工作: 查詢表:

+---------------------------------------------------------------------+ 
| ID (Primary Key) | Author | threadid | created  | Comments  | 
+---------------------------------------------------------------------+ 
| 1    | C | 237  | 2016-07-24 | Hi there... | 
| 2    | T | 421  | 2015-06-07 | Hello, ..  | 
| 3    | C | 421  | 2015-06-08 | Hi,...   | 
| 4    | C | 327  | 2017-03-13 | Hey there.. | 
+---------------------------------------------------------------------+ 

其中T代表公司如果客戶發送查詢到該公司發送查詢到客戶和C。

Enquirythreads表:

+----------------------------------+ 
| ID (Primary Key) | created  | 
+----------------------------------+ 
| 421    | 2016-07-24 | 
| 237    | 2016-07-24 | 
| 327    | 2015-06-08 | 
+----------------------------------+ 

我想輸出是:

+---------+ 
| ID  | 
+---------+ 
| 421 | 
+---------+ 

我希望所有的enquirythread IDS,使得與之相關的第一查詢製作作者T

這是我的代碼,但不工作:提前

SELECT enquirythreads.id 
FROM enquirythreads 
JOIN enquiries on enquirythreads.id = enquiries.threadid 
WHERE enquiries.threadid IN 
    (SELECT enquiries.threadid as enqid 
     FROM 
      (SELECT enquiries.threadid, min(enquiries.created) as mincreated 
      FROM enquiries 
      WHERE enquiries.author = 'T' 
      GROUP BY enquiries.threadid) x 

    ) 

感謝

+1

請標記與您正在使用的數據庫你的問題。 –

+0

您的查詢失敗的一個原因是您選擇'min(enquiries.created)',但您沒有使用它。 –

+0

@ThorstenKettner啊,我想我明白爲什麼它現在不工作 - 謝謝! – Tauseef

回答

1

一種方法是使用聚合和having

select e.threadid 
from enquiries e 
group by e.threadid 
having min(e.created) = min(case when e.author = 'T' then e.created end) 

這是說:「檢查最早created日期與'T'的最早日期相同「。

另一種方法是使用相關子查詢的where子句中:

select et.threadid 
from enquirythreads et 
where (select e2.author 
     from enquiries e2 
     where e2.threadid = et.threadid 
     order by e2.created asc 
     fetch first 1 row only 
    ) = 'T'; 
+0

嗨戈登 - 第一個代碼完美的作品,非常感謝! – Tauseef