我正在开展一个项目,要求我从草图构建一个论坛系统
但是我遇到了关于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个线程
我的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。 要明确:
在这种情况下是否可以正确执行count()函数?我的SQL无法获得高于2的数字。
答案 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