如何避免在php中循环sql查询?

如何避免在php中循环sql查询?,php,mysql,Php,Mysql,在这种情况下,在不使用php中的嵌套查询的情况下进行选择并输出它的最佳方法是什么?我更喜欢用一个查询 我的桌子是这样的: table1 id | items | ---|-------| 1 | item1 | 2 | item2 | 3 | item3 | .. | .. | table2 id | itemid | comment | ---|--------|----------| 1 | 1 | comment1 | 2 | 1 | comm

在这种情况下,在不使用php中的嵌套查询的情况下进行选择并输出它的最佳方法是什么?我更喜欢用一个查询

我的桌子是这样的:

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 | .. | .. | .. |
SELECT
    items,
    comment
  FROM
    table1 JOIN
    table2 ON table1.id = table2.itemid
这是我正在寻找的输出

item1 comment1 comment2 item2 comment3 item3 comment4 comment5 comment6
提前感谢

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 | .. | .. | .. |
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编译器,所以我想一个pesudo代码就足够了。

使用s

我使用了左连接,因此它也将返回没有注释的项目。如果不希望出现这种行为,请使用内部联接。
您将在格式化结果方面做一些小的工作,但您应该能够自己完成。

您是说加入?这是每一个SQL初学者都会遇到的一个问题,您将从w3schools.com或SQL教科书中受益匪浅。谢谢,我将尝试使用php。