我早些时候问过这个问题,但是似乎没人给我我想要的答案。
那么,我该如何结合来自两个mysql查询的数据?
专栏或我如何结合两个mysql查询,我得到每个
我在两个查询中指定的列?
查询1:
SELECT b.id, b.post_text, c.default_photo, d.first_name, e.status
FROM posts b
INNER JOIN profiles c
INNER JOIN users d
INNER JOIN friendship e
ON b.from_user = c.user_id
AND b.from_user = d.id
AND e.friend_id = b.from_user
WHERE e.status = 'Friend'
AND e.user_id = :id
ORDER BY b.id DESC
QUERY 1返回帖子。朋友发布的帖子
查询2
SELECT b.id, b.by_who_id, b.photo_dir, c.default_photo, d.first_name, e.status
FROM photos b
INNER JOIN profiles c
INNER JOIN users d
INNER JOIN follower e
ON b.by_who_id = c.user_id
AND b.by_who_id = d.id
AND e.from_user = b.from_user
WHERE e.status = 'Following'
AND e.following_who_id = :id
ORDER BY b.id DESC
现在QUERY 2返回照片。如果说我跟随“某人”,它将获取他们的照片
现在我想要的是查看朋友发帖和我关注的人的照片的组合..我该怎么做哦,我要按日期返回ORDER BY DATE,这样它才能返回
photo
photo
post
post
post
photo
post
没有办法,如果它的1个查询可能像这样,我可能会输出它
<?php
if ( !empty($two_queries_in_one) ) {
foreach($two_queries_in_one as $post) :
if ( empty($post["photo_dir"]) ) {
?>
html here
<?php
} else {?>
html here
<?php } endforeach;
}
?>
最佳答案
代码可以使用一些优化,但是思路很明确:
$combined = array();
foreach($query1 as $row)
{
$combined[$row['timestamp']][] = $row; // unix timestamp in order to sort
}
foreach($query2 as $row)
{
$combined[$row['timestamp']][] = $row; // unix timestamp in order to sort
}
ksort($combined); // sort the keys
foreach($combined as $timestamp => $rows)
{
foreach($rows as $row)
{
if(isset($row['photo_dir'])
{
// your code for the photo
}
else
{
// your code for the normal post
}
}
}
关于php - 我如何结合来自两个MySQL查询的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24905938/