我有这个问题:
select
l.lead_id, l.lead_date_received,
TIMESTAMPDIFF(MINUTE, l.lead_date_received, NOW()) AS minutes,
s.admin_id, a.name, a.email
from
leads l
inner join sales_emails s on l.lead_id = s.lead_id
inner join admin a on a.admin_id = s.admin_id
where
not exists (select 1 from comments c where l.lead_id = c.lead_id)
order by
minutes, l.lead_date_received desc
现在我想在像WHERE
这样的minutes > 30
条款中提出条件。但是,正如您所看到的,minutes
仅出现在SELECT
子句中而不是FROM
子句或子查询中,这意味着我的条件如minutes > 30
将无法在WHERE
条款。
我该如何解决这个问题?
答案 0 :(得分:2)
SELECT l.lead_id, l.lead_date_received, TIMESTAMPDIFF(MINUTE, l.lead_date_received, NOW()) AS minutes, s.admin_id,
a.name, a.email
FROM leads l
INNER JOIN sales_emails s
ON l.lead_id = s.lead_id
INNER JOIN admin a
ON a.admin_id = s.admin_id
WHERE NOT EXISTS (SELECT 1 FROM comments c WHERE l.lead_id = c.lead_id)
AND TIMESTAMPDIFF(MINUTE, l.lead_date_received, NOW()) > 30
ORDER BY minutes, l.lead_date_received DESC
或者添加另一个查询:
SELECT *
from
(
SELECT l.lead_id, l.lead_date_received, TIMESTAMPDIFF(MINUTE, l.lead_date_received, NOW()) AS minutes, s.admin_id,
a.name, a.email
FROM leads l
INNER JOIN sales_emails s
ON l.lead_id = s.lead_id
INNER JOIN admin a
ON a.admin_id = s.admin_id
WHERE NOT EXISTS (SELECT 1 FROM comments c WHERE l.lead_id = c.lead_id)
ORDER BY minutes, l.lead_date_received DESC
)
Where minutes > 30
答案 1 :(得分:1)
WITH Something as (
SELECT l.lead_id,
l.lead_date_received,
TIMESTAMPDIFF(MINUTE, l.lead_date_received, NOW()) AS minutes,
s.admin_id,
a.name, a.email
FROM leads l
INNER JOIN sales_emails s ON l.lead_id = s.lead_id
INNER JOIN admin a ON a.admin_id = s.admin_id
WHERE NOT EXISTS (SELECT top 1 1 FROM comments c WHERE l.lead_id = c.lead_id)
)
Select * FROM Something
WHERE minutes > 30
ORDER BY minutes, lead_date_received DESC