2017-04-03 81 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