1

I am beginner in MySQL. I have question about displaying data from two different table (same database), and list them based on their ID.

Recently, I am doing my project about creating simple discussion board (chat style) with features another user can comment to a post.

I have 2 tables,

Shoutbox -> Record a Discussion submit by an user

ID | Name | Text  |
1 | Iqbal  | This is Question   |
2 | Zizan | Another Question |

Comment ->> Record a Comment from another user

ID | Comment   |
1 | Answer for Iqbal |
1 | Another answer for Iqbal   |
2 | Answer for Zizan |

How do I display Comment, according to Data in Shoutbox (based on their ID) ?

So, it should like this

Discussion Board

Iqbal : This is Question
Answer : Answer for Iqbal
Answer : Another Answer for Iqbal

Zizan : Another Question
Answer : Answer for Zizan

4

3 回答 3

1

尝试这个

SELECT * FROM `Shoutbox`
LEFT JOIN `Comment` 
ON `Shoutbox`.ID = `Comment`.ID

当然要显示数据,您将有一个 while 循环在您的while

while ( ... ) {

   echo $r['Name'] . ' : ' . $r['Text'];
   echo '<br />';
   echo 'Answer :' . $r['Comment'];

   echo '<br /> <br />';
}

编辑:

如果您对每个都有多个答案,Shoutbox那么您需要执行以下操作。

注意查询的变化

SELECT * FROM `Shoutbox`
RIGHT JOIN `Comment` 
ON `Shoutbox`.ID = `Comment`.ID

和下面的代码

$finaleArray = array();
while ( $r = mysqli_fetch_array($result) ) {

   $id = $r['ID'];

   if ( !isset($finaleArray[$id]['question']) ) {
      $finaleArray[$id]['question'] = $r['Text'];
      $finaleArray[$id]['name'] = $r['Name'];
   }

   $finaleArray[$id]['answer'][] = $r['Comment'];
}

foreach( $finaleArray as $id => $a ) {
   echo $a['name'] . ' : ' . $a['question'];
   foreach($a['answer'] as $ans) {
      echo '<br />';
      echo 'Answer :' . $ans;
   }
   echo '<br /> <br />';
}

当然上面的代码有一些混淆,有什么不明白的应该问。

于 2013-10-24T06:04:08.113 回答
0

怎么样:

SELECT * FROM Shoutbox
INNER JOIN Comment 
ON Shoutbox.ID = Comment.ID
于 2013-10-24T06:07:38.687 回答
0

在评论表下创建另一个字段Shoutbox_id ,同时在评论表下插入值在评论表中传递了 Shoutbox primay id >>Shoutbox_id

然后使用 JOIN

SELECT * FROM `Shoutbox` as s
LEFT JOIN `Comment` as c
ON s.id = c.Shoutbox_id
于 2013-10-24T06:22:32.500 回答