php - MYSQL 联合排序

标签 php mysql

我现在有这个

SELECT  *
FROM    images
WHERE   images.id IN (SELECT image_id FROM image_likes WHERE user_id = '1')
    UNION
SELECT * 
FROM images
WHERE images.user_id = '1' AND upload_type in (4,3) ORDER BY id DESC

这很好用,但现在我希望它显示最近发生的结果。 例如,用户 A 上传了一张图片 -> 信息进入带有时间戳的 images。然后用户 A 喜欢其他人的图像 -> 信息进入 image_likes 并带有时间戳。现在我如何将两个时间戳列合并在一起,以便我可以按 DESC 对它们进行排序。

简要介绍一下查询的作用。 从images中选择用户在image_likes中点赞过的图片信息,然后抓取用户在images中上传的所有图片并将它们合并到一个查询中。我需要的是能够使用两个表中的 timestamp 对它们进行排序。

最佳答案

这样做怎么样??

SELECT * FROM (
    SELECT  *
    FROM    images
    WHERE   images.id IN (SELECT image_id FROM image_likes WHERE user_id = '1')
        UNION
    SELECT * 
    FROM images
    WHERE images.user_id = '1' AND upload_type in (4,3) ORDER BY id DESC
) AS a ORDER BY a.timestamp DESC;

或者更好

 (SELECT  *
    FROM images
    WHERE images.id IN (SELECT image_id FROM image_likes WHERE user_id = '1'))
        UNION
 (SELECT * 
    FROM images
    WHERE images.user_id = '1' AND upload_type in (4,3) ORDER BY id DESC)
 ORDER BY timestamp DESC

检查这个http://dev.mysql.com/doc/refman/5.5/en/union.html

更新

试试这个

 (SELECT images.id, images_likes.timestamp as timestamp FROM images JOIN images_likes 
    ON images.id=image_likes.image_id WHERE user_id = '1')
        UNION
 (SELECT images.id, images.timestamp as timestamp
    FROM images
    WHERE images.user_id = '1' AND upload_type in (4,3) ORDER BY id DESC)
 ORDER BY timestamp DESC

更新

根据您的要求进行最终查询

 (SELECT images.id, images.user_id, images.ext, images.upload_type, images_likes.timestamp as timestamp FROM images JOIN images_likes 
    ON images.id=image_likes.image_id WHERE images_likes.user_id = '1')
        UNION
 (SELECT images.id, images.user_id, images.ext, images.upload_type, images.timestamp as timestamp
    FROM images
    WHERE images.user_id = '1' AND upload_type in (4,3) ORDER BY id DESC)
 ORDER BY timestamp DESC

关于php - MYSQL 联合排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106109/

相关文章:

python - 无法为 Python v3.4.2 安装 Mysql-connector Python2.0.2

php - 为什么我尝试在这个旧的 PHP 应用程序中定义带有参数的查询时出现此错误? ( fatal error : Cannot pass parameter 2 by reference in. ..)

php:对于一个mysql表中的每条记录,显示第二个表中的所有记录

php - 将 select 语句中的 mysql 数字格式化为 php

php - 表单无需检查即可工作,但停止不会插入检查

php - 每个用户每天结构的 Mysql 访问者统计信息?

劳务发票的MySQL数据库设计问题

php - 如何在php的for循环中显示图像?

php - 如何确定从我的 html 表单中获取的输入值的数据类型,以便我可以使用它们在准备好的语句中绑定(bind)参数

php - 对 PHP func_num_args() 函数感到困惑