2010-10-26 136 views
0

什麼是在這種情況下做出選擇的最佳方式,並輸出它,而不使用PHP中的嵌套查詢?我寧願使用單個查詢來製作它。如何避免在PHP中循環sql查詢?

我的表是這樣的:

table1 

id | items | 
---|-------| 
1 | item1 | 
2 | item2 | 
3 | item3 | 
.. | .. | 


table2 

id | itemid | comment | 
---|--------|----------| 
1 | 1  | comment1 | 
2 | 1  | comment2 | 
3 | 2  | comment3 | 
4 | 3  | comment4 | 
5 | 3  | comment5 | 
6 | 3  | comment6 | 
.. | ..  | ..  | 

這就是我要找的輸出。

 
item1 
comment1 
comment2 

item2 
comment3 

item3 
comment4 
comment5 
comment6 

在此先感謝

+0

你的意思是加入? http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php – Glycerine 2010-10-26 22:23:44

+2

這是每個SQL初學者遇到的問題,您將從w3schools.com展望或sql教科書中受益。 – 2010-10-26 22:27:01

回答

4

的SQL是這樣的:

SELECT 
    items, 
    comment 
    FROM 
    table1 JOIN 
    table2 ON table1.id = table2.itemid 

(基於SQL的味道的微小變化)

(僞)代碼會看起來像這

var previousCategory : string; 
previousCategory := ""; 
foreach (var item : string in list) 
begin 
    if (item != previousCategory) 
    begin 
    Output(Newline() + sqlResult["item"] + Newline()); 
    end 
    Output(sqlResult["comment"] + Newline()) 
end 

對不起,這不是PHP,我沒有一個PHP編譯器方便,所以我想一個pududo代碼將工作得很好。

+0

謝謝,我會嘗試在PHP中。 – verx 2010-10-26 22:52:44

4

使用JOIN s。

SELECT table1.items,table2.comment 
FROM table1 
LEFT JOIN table2 ON table2.itemid=table1.id 

我用了一個LEFT JOIN,所以它會返回沒有評論的項目。如果您不想要這種行爲,請使用INNER JOIN。 您將在格式化結果時做一些小的工作,但您應該可以自行完成。