我对Facebook的查询是否有效,或者我错误配置了它

时间:2014-04-14 03:09:41

标签: mysql sql

我正在使用下面的查询创建类似Facebook的墙。

"SELECT * FROM (
            SELECT 1 AS `table`, 
            `comment_post_id` AS `feed_id`, 
            `blog_id` AS `from_blog`, 
            `comment_author` AS `author`, 
            `comment_content_stripped` AS `feed_title`, 
            `comment_content` AS `post_content_s`, 
            `type` AS `type`, 
            null AS `object_type`,
            `comment_date_gmt` AS `date` 
            FROM `wp_site_comments`
            UNION
            SELECT 2 AS `table`, 
            `post_id` AS `feed_id`, 
            null AS `from_blog`,  
            `blog_id` AS `author`, 
            `post_title` AS `feed_title`, 
            `post_content_stripped` AS `post_content_s`, 
            `post_type` AS `type`, 
            null AS `object_type`,
            `post_published_gmt` AS `date` 
            FROM `wp_site_posts`
        UNION
        SELECT 3 AS `table`, 
            `object_id` AS `feed_id`, 
            `blog_id` AS `from_blog`,  
            `user_id` AS `author`, 
            null AS `feed_title`, 
            null AS `post_content_s`, 
            `type` AS `type`, 
            `object_type` AS `object_type`,
            `date_added` AS `date` 
            FROM `wp_global_likes`
        UNION
        SELECT 4 AS `table`, 
            `object_id` AS `feed_id`, 
            null AS `from_blog`,  
            `user_id` AS `author`, 
            null AS `feed_title`, 
            null AS `post_content_s`, 
            `type` AS `type`, 
            `object_type` AS `object_type`,
            `date_added` AS `date` 
            FROM `wp_global_followers`
        ) AS tb
        ORDER BY `date` DESC"

结果返回正确,但我想知道查询是否有效或者有更好的查询来完成此任务。

1 个答案:

答案 0 :(得分:0)

您可以根据子查询的需要来ORDER BY

(SELECT …)
UNION
(SELECT …)
UNION
(SELECT …)
ORDER BY date DESC

引自the manual

  

要使用ORDER BYLIMIT子句对整个UNION结果进行排序或限制,请为各个SELECT语句添加括号并放置ORDER BY或{ {1}}在最后一个之后。

由于您可能确定不会有任何重复的行,因此您可以将隐式LIMIT更改为UNION DISTINCT,以避免不必要的删除重复项。