Php 如何组合来自两个mysql查询的数据
我早些时候问过这个问题,但似乎没有人给我我想要的答案,所以我已经回答了 那么,我如何组合来自两个mysql查询的数据呢 列或如何组合两个mysql查询,以获得每个 我在两个查询中指定的列 问题1:Php 如何组合来自两个mysql查询的数据,php,mysql,Php,Mysql,我早些时候问过这个问题,但似乎没有人给我我想要的答案,所以我已经回答了 那么,我如何组合来自两个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
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
查询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
现在查询2返回照片。如果说我跟踪“某人”,它会获取他们的照片
现在我想要的是查看朋友的帖子和我关注的人的照片。。我该怎么做哦,顺便说一句,我打算按日期订购,这样它就可以退货了
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;
}
?>
这里是html
这里是html
代码可以使用一点优化,但思路很明确:
$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代码。要将数据和输出与foreach@StefanI组合,我建议执行两个查询并使用php将它们合并到一个数组中。这是否符合我的要求,因为我在@stefan之前从未使用过数组合并对不起,我刚刚注意到它是一个空变量(数组)哈哈。但是它在ksort函数中到底包含什么呢?它包含了所有的东西吗,这意味着两个查询?好吧,据我所知,它包含了所有的数据,并按时间戳对其进行了排序?如果我错了,请纠正我。你可以按数组的键对数组进行排序。是的,在本例中,时间戳是按升序排序的。因此,首先它给数组中的每个项一个其时间戳的键,然后使用ksort对它们进行排序,然后输出准备就绪?另一件事,指定
=>$rows
的唯一时间是数组具有键的时候,如果数组没有键,那么它将被组合为$timestamp