2011-01-08 71 views
0

不太清楚我的思念,但我的SQL語句只返回一行。SQL加入只有1個返回行

SELECT 
    tl.*, 
    (tl.topic_total_rating/tl.topic_rates) as topic_rating, 
    COUNT(pl.post_id) - 1 as reply_count, 
    MIN(pl.post_time) AS topic_time, 
    MAX(pl.post_time) AS topic_bump 
    FROM topic_list tl 
    JOIN post_list pl 
     ON tl.topic_id=pl.post_parent 
    WHERE 
     tl.topic_board_link = %i 
     AND topic_hidden != 1 
    ORDER BY %s 

我有兩個表(post_list和topic_list),並post_list的post_parent鏈接到一個topic_list的topic_id。

,而不是返回所有題目(其中他們的董事會的topic_board_link爲n)的,它只返回一個話題。

+0

發佈CREATE TABLE的相關部分,包括PK/FK定義。 – Ronnis 2011-01-08 23:52:37

+0

PK post_list的是POST_ID,topic_list的PK是topic_id。我不(我認爲)有任何FK。 – 2011-01-08 23:54:43

回答

2

您通常需要一個GROUP BY子句中出現。對於需要GROUP BY的情況,MySQL與Standard SQL有不同的規則。因此,這是更接近標準SQL:

SELECT tl.*, 
     (tl.topic_total_rating/tl.topic_rates) AS topic_rating, 
     COUNT(pl.post_id) - 1 AS reply_count, 
     MIN(pl.post_time) AS topic_time, 
     MAX(pl.post_time) AS topic_bump 
    FROM topic_list AS tl 
    JOIN post_list AS pl ON tl.topic_id = pl.post_parent 
WHERE tl.topic_board_link = ? -- %i 
    AND tl.topic_hidden != 1 
GROUP BY tl.col1, ..., topic_rating 
ORDER BY ? -- %s 

在標準SQL中,你將不得不列出topic_list每一列,再加上非集合值topic_rating(您可能必須列出的表達,而不是顯示標籤或選擇列表中的列別名)。

您對'topic_board_link'也有限制條件,可能會限制您的結果集爲一個組。你不能正常使用的佔位符在ORDER BY子句中,無論是。