大家好,这是我的第一个问题,所以对我很轻松 - 需要一些帮助来提取一些数据。
这是我正在使用的两个表: 查询表:
+---------------------------------------------------------------------+
| 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 id ,以便与作者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
)
答案 0 :(得分:1)
一种方法使用聚合和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';
子句中使用相关子查询:
{{1}}