开发者

MySQL Create Summary Table?

开发者 https://www.devze.com 2023-01-07 04:28 出处:网络
I have a table of answers to questions: table questionAnswers: user VARCHAR question VARCHAR answerValue VARCHAR

I have a table of answers to questions:

table questionAnswers:
    user VARCHAR
    question VARCHAR
    answerValue VARCHAR

Important: Users can post multiple answers to questions

I want to collect how many questions a user has answered into a table:

table users
    user VARCHAR
    questionsAnswered INT

Important: Has to ignore multiple answers to the same question

Is there a single query that can automatically update the quest开发者_如何学CionsAnswered column in the users table?


UPDATE users AS u 
SET questionsAnswered = (
    SELECT COUNT(DISTINCT question) 
    FROM questionAnswers AS q 
    WHERE q.user=u.user)

This assumes that all the users in questionsAnswered already have an entry in users. (This will update users, but it won't insert any new rows.)

0

精彩评论

暂无评论...
验证码 换一张
取 消