SQL - 在这种情况下COUNT()是否可行?

时间:2013-11-04 11:09:07

标签: sql derby

我正在开展一个项目,要求我从草图构建一个论坛系统

但是我遇到了关于SQL的问题

我正在使用Derby数据库。

表格结构如下。

 

TABLE ForumThread (
    TID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 , INCREMENT BY 1) Primary Key,
    TTitle varchar(50) NOT NULL,
    UID Integer NOT NULL,
    CID Char(7) NOT NULL,
    Sticky Boolean Not null,
    Status char(1)
)

==========Content and reply of a thread========
TABLE ForumThreadContent (
    RID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 , INCREMENT BY 1) Primary Key,
    Rcontent varchar(10000) Not Null,
    RTime Timestamp Not Null,
    REditTime Timestamp,
    UID Integer NOT NULL,
    TID Integer NOT NULL,
    Status Char(1) 
)


TABLE Users (
   UID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 , INCREMENT BY 1) Primary Key,
   UName varchar(50) NOT NULL,
   UNick varchar(50) Not Null,
   ULoginName varchar(16) NOT NULL,
   Upwd varchar(16) NOT NULL,
   UPic varchar(200),
   UType Char(1) NOT NULL

)

=========Foreign Key==========
ALTER TABLE ForumThreadContent
ADD CONSTRAINT Forum_reply_fk_thread Foreign KEY (TID) REFERENCES ForumThread(TID);
Alter Table ForumThread
Add Constraint forum_thread_fk_User Foreign Key (UID) References Users(UID);

在论坛中显示单个帖子的UI设计将显示以下信息。每页显示10个线程

  • 主题标题(ForumThread.TTitle)
  • 线程作者(Users.UNick)
  • 该主题中的回复数
  • 最新回复时间(ForumThreadContent RTime)
  • 最新回复者的昵称(Users.UNick)

我的SQL声明。

SELECT ftc.tid ,ft.TTitle, ss.uNick as "Author", s.Unick as "Last replied by" , MAX(ftc.RTIME) as "Last Reply Time", COUNT(*) AS "Posts Count"
FROm ForumThreadContent ftc, Users s, ForumThread ft, Users ss
WHERE ftc.UID = s.UID
      AND ftc.TID = ft.TID 
      AND ft.UID = ss.UID
Group by ftc.tid , ft.ttitle , s.uNick , ss.uNick
Having MAX(ftc.RTIME) IN (SELECT MAX(ftcc1.RTime) 
                      FROM ForumThreadContent ftcc1 
                      WHERE ftc.TID = ftcc1.tid)

此语句可以无错误地执行。 假设在TID" 1" 中有 3个回复,当我运行它时,COUNT(*)仅计算" 2"对于tid:1。 要明确:

  • ForumThreadContent中的3行有一个外键" 1" TID
  • 第3行的第3行有一个外键" 1" UID
  • 其余的有外键" 2" UID

在这种情况下是否可以正确执行count()函数?我的SQL无法获得高于2的数字。

1 个答案:

答案 0 :(得分:1)

这可能适合你。请检查列名称

SELECT t1.tid, t1.Title, t1.Author, s1.Unick as 'Last replied by', ftc1.Rtime as 'last reply time', t1.count
FROM
(SELECT ftc.tid, ft.Title, s.UID, s.Unick as 'Author', COUNT(*) as count FROM 
ForumThreadContent ftc, Users s, ForumThread ft
where ftc.TID = ft.TID
and ft.UID = s.UID
group by ftc.tid, ft.title, s.UID) t1, Users s1, ForumThreadContent ftc1
where ftc1.rtime = (select max(rtime) from ForumThreadContent ftc2 where ftc2.tid = t1.tid)
and ftc1.uid = s2.uid