我在我的數據庫中的兩個表:如何限制連接查詢的結果?
類別
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
使用「按組」,「選擇不同的」或:http://www.sqlteam.com/article/ how-to-use-group-by-distinct-aggregates-and-derived -tables – paulsm4 2012-07-23 20:04:54
不是'distinct'確保我只得到每個項目的1個結果嗎? – user6669 2012-07-23 20:06:12
是的,如果您只想要一個類別/消息或一個消息/類別。我以爲你在問什麼...... – paulsm4 2012-07-23 20:10:03