doujiu4643 2014-09-10 10:03
浏览 71
已采纳

在SQLite3中查看

I have little troubles with my SQL code. I have following table:

CREATE TABLE post (
    post INTEGER,
    content TEXT,
    time INTEGER,
    owner TEXT,
    thread TEXT, 
    pharse TEXT);

Of course the table have default values, options, etc. owner has a foreign key to another table with users. Column thread could have multiple same values.

I want to build a view like this:

CREATE VIEW thread AS
SELECT 
    thread,
    MIN(time) AS creation,
    owner,
    pharse,
    MAX(time) AS last,
    COUNT(post) as count
FROM post
GROUP BY thread
ORDER BY time DESC;

thread group my view, creation is a creation time of first post, owner is a creator of first post, pharse is a pharse of first post, last is a creation time of last post, and count is a count of all posts with a same thread value.

And everything would be fine except the MAX(time) AS last, this column forces the view to show the owner of the last post, when I want to see the owner of first. When I kick off that line from code everything works fine, but I need it to sort my view, and this is only cause I want to keep it - for sorting.

Order of columns has no mean for me. I'm using this queries in PHP if it has any importance.

If there would be another way or somebody could tell me how to fix my code I will be pleased.

  • 写回答

1条回答 默认 最新

  • duandangqin0559 2014-09-10 10:10
    关注

    To prevent the MAX() from influencing the rest of the query, you have to move it into a subquery:

    SELECT thread,
           MIN(time) AS creation,
           owner,
           pharse,
           (SELECT MAX(time)
            FROM post AS p2
            WHERE p2.thread = post.thread
           ) AS last,
           COUNT(post) as count
    FROM post
    GROUP BY thread
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题