2017-10-13 45 views
-1

我有2個表格「文本」和「作者」。我想獲得最新的文本(由pubDate排序)每個作者。當我嘗試使用「Group By」時,它返回一個錯誤。使用「分組依據」與「加入」在Mysql

這裏是我的表:

作者:

+----+-------+--+ 
| id | name | | 
+----+-------+--+ 
| 1 | cat | | 
| 2 | bird | | 
| 3 | dog | | 
| 4 | horse | | 
+----+-------+--+ 

文本:

+----+----------+------------------+------------+ 
| id | authorID |  title  | pubDate | 
+----+----------+------------------+------------+ 
| 1 |  1 | Life About Cat | 2017-10-13 | 
| 2 |  1 | How to be a cat? | 2017-10-12 | 
| 3 |  2 | Is flying?  | 2017-10-13 | 
| 4 |  2 | We love cats. | 2017-10-11 | 
+----+----------+------------------+------------+ 

這裏是我工作的SQL查詢沒有 「分組依據」

SELECT texts.id AS textID, texts.title, texts.authorID 
FROM texts JOIN authors ON authors.id = texts.authorID 
WHERE authors.pin != '1' AND authors.status='1' 
ORDER BY texts.pubDate DESC LIMIT 8 

這裏不起作用查詢與「分組依據」

SELECT texts.id AS textID, texts.title, texts.authorID 
FROM texts GROUP BY texts.authorID JOIN authors ON authors.id = texts.authorID 
WHERE authors.pin != '1' AND authors.status='1' 
ORDER BY texts.pubDate DESC LIMIT 8 

我怎樣才能從每個作者的最新文本?

+0

您是否閱讀過['SELECT'語句](https://dev.mysql.com/doc/refman/5.7/en/select.html)的文檔?它解釋了「GROUP BY」子句的放置位置(但它並沒有教你「GROUP BY」對於你當前的目標完全沒有用處)。 – axiac

+0

爲什麼要在沒有聚合函數時使用Group By子句。如果有任何錯誤,請使用第一個查詢並向我們顯示預期的和實際的結果。還張貼一些示例數據。 –

+0

'GROUP BY' **不會從表中返回行。它會生成它返回的記錄。因此它不能用於*從每個作者*獲取最新的文本。搜索標籤爲[tag:greatest-n-per-group]的類似問題 – axiac

回答

0

試試這個 - 下面的查詢

SELECT A.name 
     ,T.title 
     ,MAX(pubDate) 
FROM AUTHORS A 
INNER JOIN TEXTS T ON A.ID = T.authorID 
GROUP BY A.name 
     ,T.title 
0

嘗試。

select * from Authors as a 
Inner join (
select MAX(pubDate) , author_id, title from `Text` group by author_id 
) as t 
ON t.author_id = a.id