SQL查询可获取10个带有回复的最新主题

时间:2018-08-04 14:45:53

标签: sql database

我有一个简单的论坛数据库,想编写SQL查询来获取 来自 3个或更多独特海报的10个最新主题(主题)。 结果:主题(线程)名称|最后留言文字|用户名|日期 IMG1

已更新: 这是我尝试过的:

SELECT thread.thread_id, thread.thread_name, message.thread_id, 
COUNT(message.thread_id) 
FROM thread, message
WHERE message.thread_id = thread.thread_id
GROUP BY message.thread_id
HAVING COUNT(message.thread_id) >= 3
LIMIT 10

但是它返回10个主题(主题),并带有3个或更多回复(但不包含3个或更多独特的发帖人)

更新2:

SELECT message.thread_id AS ID, thread.thread_name AS topic
FROM message INNER JOIN thread
ON message.thread_id = thread.thread_id
GROUP BY message.thread_id
HAVING COUNT(*) >= 3
LIMIT 10

这还将返回10个主题,且有3个或更多回复

更新3,谢谢@ shawnt00

SELECT thread.thread_name AS 'Topic', message_text AS 'Message', person_nickname AS 'Nickname', message_date AS 'Date'
FROM thread,
(
    SELECT thread.thread_id, MAX(message_date) AS last_date
    FROM thread 
    INNER JOIN message ON message.thread_id = thread.thread_id
    GROUP BY thread.thread_id
    HAVING COUNT(DISTINCT message.person_id) >= 3
) AS temp
INNER JOIN message
ON message.thread_id = temp.thread_id AND message.message_date = temp.last_date
INNER JOIN person ON person.person_id = message.person_id
WHERE thread.thread_id = temp.thread_id
ORDER BY message.message_date DESC
LIMIT 10

2 个答案:

答案 0 :(得分:0)

我认为您需要以下查询。 假设您使用的是mysql,那么我想根据需要使用ex_text='This is an example list that has no special keywords to sum up the list, but it will do. Another list is a very special one this I like very much.' tokenized = word_tokenize(ex_text) stop_words = set(stopwords.words('english')) stop_words.update([".", ","]) #Since I do not need punctuation, I added . and , stopword_pos_set = set() # I need to note the position of all the stopwords for later use for w in tokenized: if w.lower() in stop_words: indices = [i for i, x in enumerate(tokenized) if x == w] stopword_pos_set.update(indices) stopword_pos = sorted(list(stopword_pos_set)) # set to list # Replacing stopwords with "QQQQQ" for i in range(len(stopword_pos)): tokenized[stopword_pos[i]] = 'QQQQQ' print(tokenized) print(stopword_pos) 函数的最后3个唯一行

import { HashRouter as Router } from 'react-router-dom'

但是如果数据库是SQLSERVER,则使用以下查询

Limit

答案 1 :(得分:0)

with data as (
    select p.thread_id, max(message_date) as last_date
    from thread t inner join message m on m.thread_id = t.thread_id
    group by p.thread_id
    having count(distinct m.person_id) >= 3
)
select *
from data d
    inner join message m
        on m.thread_id = d.thread_id and m.message_date = m.last_date
    inner join person p on p.person_id = m.person_id;

唯一的假设是日期上没有联系。如果您有可用的分析功能,那么还有其他使用这些功能的方法。我相信您可以弄清楚如何获得前10名。