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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办