这是我的问题:
SELECT e.id, (SELECT MIN(u.id) id
FROM (SELECT MIN(id) id
FROM events
WHERE author_id = 32
GROUP BY type, post_id, table_code, comment_id, context
ORDER BY MIN(id) desc
LIMIT 15) as u
) as indicator_id
FROM events e
WHERE author_id = 32
HAVING e.id >= indicator_id
ORDER BY id DESC
它也有效,并返回两列:id
和indicator_id
。
我需要得到id
。如何省略indicator_id
?如您所见,我需要将indicator_id
用于HAVING
子句。所以我不能省略整个子查询。我需要将它移到除SELECT
语句之外的其他地方。语法是什么?
答案 0 :(得分:2)
您可以将子查询移动到having
子句。正如戈登回答的那样,你使用having
子句作为第二个where
,只有MySQL支持。最好使用where
向and
添加第二个条件:
SELECT e.id
FROM events e
WHERE author_id = 32
AND e.id >= (SELECT MIN(u.id) id
FROM (SELECT MIN(id) id
FROM events
WHERE author_id = 32
GROUP BY type, post_id, table_code, comment_id, context
ORDER BY MIN(id) desc
LIMIT 15) as u
)
ORDER BY id DESC
根据您的评论,这会更简单一些。它选择具有最高事件ID的15个帖子:
SELECT id
FROM events
WHERE author_id = 32
AND post_id IN
(
SELECT DISTINCT post_id
FROM events
ORDER BY
id DESC
LIMIT 15
)
答案 1 :(得分:1)
你不能,但你可以将逻辑移到FROM
条款:
SELECT e.id
FROM events e JOIN
(SELECT MIN(u.id) as id
FROM (SELECT MIN(id) as id
FROM events
WHERE author_id = 32
GROUP BY type, post_id, table_code, comment_id, context
ORDER BY MIN(id) desc
LIMIT 15
) u
) e15
ON e.id >= e15.id
WHERE e.author_id = 32
ORDER BY e.id DESC;
我更喜欢这种配方,因为它是标准的SQL。您对HAVING
子句的使用是MySQL扩展。
答案 2 :(得分:1)
您还可以声明一个表并在其中插入指标ID记录,并在查询中使用它。我知道这太长了,但还有一种方法可以做到。
Declare @indicatoridtable table
(
@indicatorid datatype
)
Insert into @indicatoridtable
SELECT MIN(u.id) as id
FROM (SELECT MIN(id) as id
FROM events
WHERE author_id = 32
GROUP BY type, post_id, table_code, comment_id, context
ORDER BY MIN(id) desc
LIMIT 15
)
SELECT e.id
FROM events e
ON e.id >= (select top 1 @indicatorid from @indicatoridtable )
WHERE e.author_id = 32
ORDER BY e.id DESC;