合并多个 SQL 查询的结果(由于列名不同,因此无法合并 UNION)


Combine results of multiple SQL queries (UNION not possible because column names are different)

我想制作一个通知页面,显示有关各种事物的通知,例如新关注者,新喜欢,新评论等。我想显示一个列表,按时间顺序显示所有这些内容。

我的表如下所示:

COMMENT
1   comment__id
2   comment__user_id
3   comment__snap__id
4   comment__text
5   comment_add_time
LIKE
1   like__id
2   like__user__id
3   like__snap__id
4   like__like_time
FOLLOW
1   follow__id
2   follower__user__id
3   followed__user__id
4   follow__follow_time
5   follow__request_status

我会用这样的查询加载用户的关注者:

try {
    $select_followers_query = '
    SELECT follow.follower__user__id, follow.followed__user__id, follow.follow__request_status, user.user__id, user.user__username, user.user__profile_picture, user.privacy
    FROM follow
    JOIN user ON(follow.follower__user__id = user.user__id) 
    WHERE followed__user__id = :followed__user__id';
    $prep_select_followers = $conn->prepare($select_followers_query);
    $prep_select_followers->bindParam(':followed__user__id', $get_user__id, PDO::PARAM_INT);
    $prep_select_followers->execute();
    $followers_result = $prep_select_followers->fetchAll();
    $followers_count = count($followers_result);
}   
catch(PDOException $e) {
    $conn = null;
    echo $error;
}

接下来,我得到这样的结果:

foreach($followers_result AS $followers_row) {
    $follower_user_id = $followers_row['follower__user__id'];
    // the rest of the variables will come here...
}

我将有单独的SQL查询,例如上面的查询,每个查询都加载一些东西。上面的例子加载关注者,另一个查询将加载评论等。我想显示所有这些查询的结果,并按时间顺序显示它们,如下所示:

@user_1 liked your photo
@user_4 started following you
@user_2 commented on your photo
etc...

我怎样才能做到这一点?SQL UNION 要求表具有相同的列数,并且所选列必须具有相同的名称。我没有这些。此外,每种结果(关注者、评论者或喜欢(都会有不同的标记。关注者通知将有一个关注按钮,评论通知将有一个按钮,该按钮将重定向到喜欢的照片等。

SQL UNION 要求表具有相同的列数,并且所选列必须具有相同的名称。

不,它没有。这里的表"a"有两列,整数和varchar。

create table a (
  a_id integer,
  a_desc varchar(10)
);
insert into a values (1, 'aaaaaaaa'), (2, 'bbbbbbbb');

表 "b" 有三列,即 varchar、date 和 char。

create table b (
  b_id varchar(10),
  created_date date,
  unused char(1)
);
insert into b values ('xyz', '2014-01-01', 'x'), ('tuv', '2014-01-13', 'x');

SQL 联合运算符仅要求 SELECT 子句(而不是表(具有相同数量的列,并且它们具有兼容的数据类型。通常可以将不兼容的类型强制转换为更有用的类型。

-- SELECT clause has three columns, but table "a" has only two.
-- The cast is for illustration; MySQL can union an integer with a 
-- varchar without a cast.
--
select cast(a_id as char) as col_1, a_desc as col_2, null as col_3
from a
union all
-- Note that these columns don't have the same names as the columns
-- above.
select b_id, null, created_date 
from b;

您可以将单个列用于日期和 varchar,但这通常不是一个好主意。(将日期与明显不是日期的东西混合通常不是一个好主意。

select cast(a_id as char) as col_1, a_desc as col_2
from a
union all
select b_id, created_date 
from b;
您可以使用

UNION,但您需要使用"AS"为列指定相同的名称。您还需要为每个选择添加如下行:

, 'comment' as Type FROM comment

和:

, 'follow' as Type FROM follow