0

我不知道怎么做这个。


背景:

配置文件 -> 包含用户配置文件的表格

分数 -> 用户分数表(一个用户可以有多个分数)(这个表有一个 created_at 字段可以知道我何时引入新分数)

想象一下得分表保存 klout 得分数据。


如何将此查询转换为视图?

SELECT  t1.id, 
    t1.name, 
    t1.screen_name, 
    t1.description, 
    t1.url, 
    t1.statuses_count, 
    t1.followers_count, 
    t1.friends_count, 
    t1.listed_count, 
    t1.favourites_count, 
    t1.utc_offset, 
    t1.time_zone, 
    t1.verified, 
    t1.lang, 
    t1.profile_image_url, 
    t1.geo_enabled, 
    t1.location, 
    t1.lat, 
    t1.lng, 
    t1.created_at, 
    t3.score, 
    t3.delta, 
    t3.detail
        FROM profiles t1 LEFT JOIN (SELECT t2.user_id, t2.score, t2.delta, t2.detail
                                                    FROM scores t2
                                                    ORDER BY t2.created_at DESC) 
                AS t3 ON t3.user_id = t1.id
        GROUP BY t1.id
4

2 回答 2

4

问题VIEW不能包含subquery,因为您没有执行任何聚合,查询中的子查询可以直接连接到表上。

CREATE VIEW viewName
AS
SELECT  t1.id, 
        t1.name, 
        t1.screen_name, 
        t1.description, 
        t1.url, 
        t1.statuses_count, 
        t1.followers_count, 
        t1.friends_count, 
        t1.listed_count, 
        t1.favourites_count, 
        t1.utc_offset, 
        t1.time_zone, 
        t1.verified, 
        t1.lang, 
        t1.profile_image_url, 
        t1.geo_enabled, 
        t1.location, 
        t1.lat, 
        t1.lng, 
        t1.created_at, 
        t3.score, 
        t3.delta, 
        t3.detail
FROM    profiles t1 
        LEFT JOIN scores t3
            ON t3.user_id = t1.id
-- GROUP BY t1.id

我不明白为什么你GROUP BY的查询中有一个子句。

于 2013-01-22T15:59:10.963 回答
0

您可以将代码拆分为 2 个视图

视图 1:

CREATE VIEW step1

AS

SELECT t2.user_id, t2.score, t2.delta, t2.detail
FROM scores t2
ORDER BY t2.created_at DESC

视图 2:

CREATE VIEW step2

AS

SELECT  t1.id, 
                t1.name, 
                t1.screen_name, 
                t1.description, 
                t1.url, 
                t1.statuses_count, 
                t1.followers_count, 
                t1.friends_count, 
                t1.listed_count, 
                t1.favourites_count, 
                t1.utc_offset, 
                t1.time_zone, 
                t1.verified, 
                t1.lang, 
                t1.profile_image_url, 
                t1.geo_enabled, 
                t1.location, 
                t1.lat, 
                t1.lng, 
                t1.created_at, 
                t3.score, 
                t3.delta, 
                t3.detail
FROM profiles t1 
     LEFT JOIN step1 AS t3 ON t3.user_id = t1.id
GROUP BY t1.id

我不确定你为什么按 t1.id 分组,但也许你的数据中有一些我不知道的东西

于 2013-01-22T16:25:15.317 回答