[英]How to sort groups in MySQL join operator?
在我的SQL我有這個查詢
SELECT * FROM threads t
JOIN (
SELECT c.*
FROM comments c
WHERE c.thread_id = t.id
ORDER BY date_sent
ASC LIMIT 1
) d ON t.id = d.thread_id
ORDER By d.date_sent DESC
基本上我有兩個表,線程和注釋。 注釋具有線程表的外鍵。 我想為每個線程行獲取earliest
注釋行。 主題至少應有1條評論。 如果沒有,則不應包含線程行。
在上面的查詢中,我在線程上進行了選擇,然后將其與自定義查詢結合在一起。 我想使用t.id,其中t是方括號外的選擇表。 在方括號內,我創建了一個新的結果集,該注釋用於當前線程。 我在那里進行排序和限制。
然后,我再次對其進行排序,因此其最早出現在頂部。 但是,當我運行此命令時,它給出錯誤#1054 - Unknown column 't.id' in 'where clause'
。
有人知道這是怎么回事嗎?
謝謝
unknown column t.id
是由於以下事實造成的:別名t
在子查詢中是未知的,但實際上確實不需要它,因為您在ON
子句中加入了它。
代替LIMIT 1
,在子查詢中使用按thread_id
分組的MIN(date_sent)
聚合。 如果兩個表中的列具有相同的名稱,請在聯接查詢中也使用SELECT *
。 最好明確列出這些列。
SELECT
/* List the columns you explicitly need here rather than *
if there is any name overlap (like `id` for example) */
t.*,
c.*
FROM
threads t
/* join threads against the subquery returning only thread_id and earliest date_sent */
INNER JOIN (
SELECT thread_id, MIN(date_sent) AS firstdate
FROM comments
GROUP BY thread_id
) earliest ON t.id = earliest.thread_id
/* then join the subquery back against the full comments table to get the other columns
in that table. The join is done on both thread_id and the date_sent timestamp */
INNER JOIN comments c
ON earliest.thread_id = c.thread_id
AND earliest.firstdate = c.date_sent
ORDER BY c.date_sent DESC
邁克爾的答案是正確的。 這是與您的查詢形式相似的另一個答案。 您可以按照關聯子查詢的方式進行操作,然后加入其他信息:
SELECT *
FROM (SELECT t.*,
(SELECT c.id
FROM comments c
WHERE c.thread_id = t.id
ORDER BY c.date_sent ASC
LIMIT 1
) as mostrecentcommentid
FROM threads t
) t JOIN
comments c
on t.mostrecentcommentid = c.id
ORDER By c.date_sent DESC;
這樣做可能會具有更好的性能,因為它不需要匯總所有數據。 但是,為了提高性能,您需要在comments(thread_id, date_set, id)
上建立索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.