2010-10-26 93 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。 您将在格式化结果时做一些小的工作,但您应该可以自行完成。