You can run the following query to get a list of users who voted and their selected poll options.
Please choose the appropriate query for your Discourse version.
Query for Discourse v2.2.0.beta5 and newer
-- [params]
-- post_id :post_id
-- text :poll_name = poll
SELECT u.id AS user_id, u.username, v.poll_option_id AS option_id, o.html AS option_html
FROM polls p
JOIN poll_votes v ON (p.id = v.poll_id)
JOIN poll_options o ON (o.id = v.poll_option_id)
JOIN users u ON (v.user_id = u.id)
WHERE p.post_id = :post_id AND p.name = :poll_name
ORDER BY u.username, v.poll_option_id
Query for older versions of Discourse up to v2.2.0.beta4
-- [params]
-- post_id :post_id
-- text :poll_name = poll
SELECT votes.user_id, users.username, votes.option_id, options.html AS option_html
FROM (
SELECT value1 ->> 'id' AS id,
value1 ->> 'html' AS html
FROM (
SELECT json_array_elements(value :: JSON -> :poll_name -> 'options') AS value1
FROM post_custom_fields
WHERE post_id = :post_id AND name = 'polls' AND value :: JSON -> :poll_name ->> 'name' = :poll_name
) option_values
) options
JOIN (
SELECT key :: INTEGER AS user_id,
trim(json_array_elements(value :: JSON -> :poll_name) :: TEXT, '"') AS option_id
FROM json_each((
SELECT value :: JSON
FROM post_custom_fields
WHERE post_id = :post_id AND name LIKE 'polls-votes'
))
) votes ON (options.id = votes.option_id)
JOIN users ON (votes.user_id = users.id)
ORDER BY users.username, votes.option_id
How to find post_id
You can use the following query if you need to find the right post_id
.
-- [params]
-- topic_id :topic_id
-- int :post_number = 1
SELECT id
FROM posts
WHERE topic_id = :topic_id AND post_number = :post_number