2012-07-23 43 views
2

我在我的數據庫中的兩個表:如何限制連接查詢的結果?

類別

id 
category 
message 

消息

id 
title 
message 

我試圖找回他們的類別兩條消息。每條消息可以有多個類別。我試着用下面的查詢:

SELECT categories.category, messages.id, messages.title, messages.message 
FROM categories 
RIGHT JOIN messages 
ON messages.id = category.message 
ORDER BY messages.id DESC 
LIMIT 2 
OFFSET 0 

這樣做的輸出中是一樣的東西:

category id title  message 
test-cat 1 Test title This is the message body 
category2 1 Test title This is the message body 

但是這個查詢結果中只有兩排(因爲這是檢索到的消息有多個類別) 。我如何限制消息的數量而不是類別的數量?這樣的結果是這樣的:

category id title  message 
test-cat 1 Test title This is the message body 
category2 1 Test title This is the message body 
test-cat 2 Another msg This is content 
test-cat2 2 Another msg This is content 
something 2 Another msg This is content 
+0

使用「按組」,「選擇不同的」或:http://www.sqlteam.com/article/ how-to-use-group-by-distinct-aggregates-and-derived -tables – paulsm4 2012-07-23 20:04:54

+1

不是'distinct'確保我只得到每個項目的1個結果嗎? – user6669 2012-07-23 20:06:12

+0

是的,如果您只想要一個類別/消息或一個消息/類別。我以爲你在問什麼...... – paulsm4 2012-07-23 20:10:03

回答

3

把限制在一個子查詢:

SELECT categories.category, m.id, m.title, m.message 
FROM categories RIGHT JOIN 
    (select * 
     from messages 
     ORDER BY messages.id DESC 
     limit 2 
    ) m 
    ON m.id = categories.message 
ORDER BY m.id DESC 
+0

你完全正確@ruakh。 – 2012-07-23 20:12:01

+0

我嘗試使用該錯誤時出現錯誤:('致命錯誤:未收到的異常'PDOException',消息'SQLSTATE [42P01]:未定義的表:7錯誤:缺少表「m」的FROM-clause條目LINE 1:.. .M類別RIGHT JOIN(SELECT * from messages ORDER BY m.id DESC ... ^' – user6669 2012-07-23 20:21:47

+0

我錯誤地將類別的名稱設置爲「category」。現在應該可以。 – 2012-07-23 20:22:39