我正在努力使功能类似于facebook的通知窗口。它们的功能似乎结合了任何类型的事件并在日期之后显示它们。
所以我有2张桌子: 文章和评论。 两者都有两个相似的行:uniquepostowner和date_posted。
我想加入他们并一个接一个地展示他们。 示例:
User A has posted a comment (04.05.2012 5:30)
User B Has posted a comment (04.05.2012 6:30)
User C has written an article (04.05.2012 7:30)
user D has posted a comment (04.05.2012 8:30)
然而,我正在努力加入这两个并显示结果。 阅读其他类似场景我已经尝试过这个查询:
$sesid = $_SESSION['user_id'];
$sql = "SELECT X.* FROM ( SELECT * FROM `article` WHERE uniquepostowner = {$sesid} UNION SELECT * FROM `comments` WHERE uniquepostowner = {$sesid} ) X ORDER BY X.`date_posted`";
$result = mysql_query($sql);
然后尝试获取结果:
while($row = mysql_fetch_array($result))
{
echo $row['article.id'];
}
表:
**article**:
id
title
content
uniqueuser
date_posted
full_name
uniquepostowner
**comments**:
id
pid (same as article.id)
date_posted
content
full_name
uniquepostowner
这些表有更多行,但它们无关紧要。 但没有成功。任何帮助一如既往地非常感谢! :)
目前我正在尝试这个,但它没有做我想要的。
$sql = "SELECT * FROM article a INNER JOIN comments c WHERE a.uniquepostowner = {$sesid} AND c.uniquepostowner = {$sesid}
ORDER BY a.date_posted DESC , c.date_posted DESC ";
答案 0 :(得分:3)
我认为这就是你所需要的:
<强>更新:强>
$sesid = $_SESSION['user_id'];
$sql = "
SELECT
X . *
FROM
(SELECT
id,
date_posted,
content,
full_name,
uniquepostowner,
'article' AS type
FROM
article
WHERE
uniquepostowner = {$sesid} UNION SELECT
id,
date_posted,
content,
full_name,
uniquepostowner,
'comment' AS type
FROM
comments
WHERE
uniquepostowner = {$sesid}) X
ORDER BY X.date_posted
";
$result = mysql_query($sql);
你可以用:
进行迭代while($row = mysql_fetch_array($result))
{
if($row['type']=='article'){
echo "User " . $row['full_name'] . " has written an article (".$row['date_posted'].")<br>";
} else {
echo "User " . $row['full_name'] . " has posted a comment (".$row['date_posted'].")<br>";
}
}
您可以在以下网址查看:
答案 1 :(得分:2)
你应该尝试将你的sql改为仅使用两个表共有的列:
SELECT uniquepostowner,date_posted FROM `article` WHERE uniquepostowner = {$sesid}
UNION
SELECT uniquepostowner,date_posted FROM `comments` WHERE uniquepostowner = {$sesid}
ORDER BY date_posted
mysql manual中还有一些例子。
答案 2 :(得分:0)
也许我错过了这一点,但这并不能解决问题:
SELECT articles.*, comments.* FROM articles, comments WHERE articles.uniqueuserid = $userId AND comments.postId = articles.Id ORDER BY articles.date_published DESC
Ofc所有表格和字段名称都需要调整以适合您的代码。 它的作用基本上是加载所有带有uniquepostowner的文章或任何你的名字,以及按发布日期排序的相应评论。
这就是你想要的吗?
修改强> 实际上,评论和文章是特殊的,你想并排显示它们?在这种情况下,为什么不要创建活动&#39;表,其中包含日期,所有者,类型(文章/评论/喜欢/照片/任何内容)和相应项目的ID,并使用它来生成您的Feed?
答案 3 :(得分:0)
您必须在联合的每个查询上使列相等:
SELECT X.* FROM ( SELECT **uniquepostowner** FROM `article` WHERE uniquepostowner = {$sesid} UNION SELECT **uniquepostowner** FROM `comments` WHERE uniquepostowner = {$sesid} ) X ORDER BY X.`date_posted`
这只是一个例子,在联合中,两个查询都必须返回相同数量的字段,我觉得你只返回两个表共有的filds。