我正在尝试制作私人消息应用程序。我需要收件箱显示“主要消息”和“消息答案”。
我的表格如下:
发表
id - header - content - from_user - to_user - receiver_opened - user_bywho - timestamp。
post_answer
id - answer_from_user - answer_to_user - answer_user_bywho - answer_header - answer_content - answer_id - timestamp_svar。
现在我遇到了麻烦。因为我不知道如何做到这一点。
我的mysql_query现在看起来像这样:
$user = $_SESSION['username'];
$sql = mysql_query("SELECT * FROM post,post_answer WHERE ".
"answer_to_user='$user' AND to_user='$user'")
or die(mysql_error());
提前致谢。
答案 0 :(得分:2)
该查询无效,因为它对id
字段不明确。
为此,您可以使用JOIN
SELECT *
FROM post
INNER JOIN post_answer
WHERE post.to_user = post_answer.answer_to_user
SELECT post.id,
header,
content,
from_user,
to_user,
receiver_opened,
user_bywho, timestamp,
post_content.id,
answer_from_user,
answer_to_user,
answer_user_bywho,
answer_header,
answer_content,
answer_id,
timestamp_svar
FROM post,
post_content
WHERE answer_to_user=$user AND
to_user=$user
希望这有帮助
假设您的表包含像
这样的字段看看你是否在数组中得到结果$results
。
foreach ($results as $result)
{
echo $result->firstname;
echo $result->lastname;
echo $result->number;
}
答案 1 :(得分:0)
答案 2 :(得分:0)
SELECT * FROM POST INNER JOIN POST_ANSWER WHERE
POST.TO_USER = POST_ANSWER.ANSWER_TO_USER
答案 3 :(得分:0)
试试这个:
$sql = mysql_query("SELECT *
FROM post p, post_answer pa
WHERE ".
"pa.answer_to_user='$user' AND p.to_user='$user'")
or die(mysql_error());
您为表提供别名并使用别名指定哪个表包含WHERE子句中的哪一列。
答案 4 :(得分:0)
我认为你不想把它们放在一个查询中,或者至少不是你在那里提供的查询。
此查询:
SELECT * FROM post,post_answer WHERE answer_to_user='$user' AND to_user='$user'
将导致一行包含太多列:
id - header - content - from_user - to_user - receiver_opened - user_bywho - timestamp - answer_from_user - answer_to_user - answer_user_bywho - answer_header - answer_content - answer_id - timestamp_svar
此查询将提供满足您所有要求的所有帖子。
-- look for all posts to the user
SELECT * FROM POST WHERE to_user = '$user'
UNION DISTINCT
-- look for all posts where an answer exists which is to the user.
SELECT * FROM POST P WHERE EXISTS
( SELECT 1 FROM post_answer PA WHERE P.ID = PA.ID AND
answer_to_user = '$user' );
然后你应该在一个单独的查询中查找POST_ANSWERS - 这些是单独的数据,实际上你不应该从同一个请求中获取它们。