我有以下表格:
1用户
username
user_id
full_name
password
location
interests
2个问题的
q_content
q_id
q_category
q_user_id(the username of user who asked the question)
3-答案
a_id
a_content
a_user_id
q_id
我正在尝试在单个页面上输出带有答案的问题,但我不知道如何将问题与他们的答案联系起来。对一个问题的多个答案,这变得更加困难。
我在XAMPP上使用mySql,localhost。非常感谢任何帮助。
更新
<?php
$output = mysqli_query($link,$sql);
if (mysqli_num_rows($output) >= 0) {
while ($row = mysqli_fetch_assoc($output)){
echo $row["q_content"]."<br>".$row["a_content"]."<br>"."<br>";
}
} else{
echo "error" . mysqli_error($link);
} // } -- You had an extra brace here
我使用了第一种方法,这是我的输出代码,但它无法正确显示。我怎么纠正这个,没有创建数组。
答案 0 :(得分:0)
SELECT * FROM question;
注意,如果问题表太大,您必须使用限制逐页显示。
例如,要显示每页10条记录的第二页,查询必须如下所示:
SELECT * FROM question LIMIT 11, 10
SELECT * FROM answers WHERE answers.q_id = :question_id
要防止n + 1问题,请在一个查询中选择所有答案并使用php解析结果。请改用以下查询:
SELECT * FROM answers WHERE answers.q_id IN :question_ids
其中quetion_ids
是当前页面上的问题ID。
答案 1 :(得分:0)
与上面提到的其他答案一样,您可以选择所有问题,然后对每个问题的所有答案运行查询,但效率非常低。
为了在单个查询中完成此操作,有以下两个选项:
一个选项是使用JOIN并将每个答案放在自己的行上,但按问题排序,所以PHP(循环显示时),可以 让它跳过重复。
SELECT
QuestionTbl.content AS `question`,
QuestionTbl.category,
AnswerTbl.content AS `answer`,
AskerTbl.full_name AS `asker`,
AnswererTbl.full_name AS `answerer`
FROM
`question` AS QuestionTbl
LEFT JOIN
`answers` AS AnswerTbl
ON QuestionTbl.q_id = AnswerTbl.q_id
INNER JOIN
`users` AS AskerTbl
ON QuestionTbl.q_user_id = AskerTbl.user_id
INNER JOIN
`users` AS AnswererTbl
ON AnswerTbl.a_user_id = AnswererTbl.user_id
ORDER BY
QuestionTbl.content ASC,
AnswerTbl.content ASC;
相应的PHP代码(结构)将是:
<?php
// Assuming an associative array stored in $result
$question = NULL;
foreach($result as $row){
if($question != $row['question']){
// Display question
// The question is $row['question']
// Update question store
$question = $row['question'];
}
// Display answer(s)
}
另一种选择是使用GROUP_CONCAT
将所有答案放在一起,但这可能会变得混乱。如果你已经循环,我会推荐第一个,但这里是:
SELECT
QuestionTbl.content AS `question`,
QuestionTbl.category,
AskerTbl.full_name,
GROUP_CONCAT(
CONCAT(
AnswerTbl.content,
'&&',
AnswererTbl.full_name
)
SEPARATOR '||'
) AS `answers`
FROM
`question` AS QuestionTbl
LEFT JOIN
`answers` AS AnswerTbl
ON QuestionTbl.q_id = AnswerTbl.q_id
INNER JOIN
`users` AS AskerTbl
ON QuestionTbl.q_user_id = AskerTbl.user_id
INNER JOIN
`users` AS AnswererTbl
ON AnswerTbl.a_user_id = AnswererTbl.user_id
GROUP BY
QuestionTbl.content,
QuestionTbl.category,
AskerTbl.full_name
ORDER BY
QuestionTbl.content ASC,
AnswerTbl.content ASC;
然后相应的PHP结构将是:
<?php
// Assuming an associative array stored in $result
foreach($result as $row){
// Display question
// The question is $row['question']
$answers = explode('||', $row['answers]);
// Loop through
foreach($answers as $answer) {
$components = explode('&&', $answer);
// Display answer
// The answer is $components[0];
// The answerer is $components[1];
}
}
就个人而言,我更喜欢第一个,因为我发现它更干净,如果GROUP_CONCAT
的指定分隔符在答案文本中,第二个可能会导致问题,所以你必须过滤它。