Hello folks! I've got a fun SQL problem for y'all.
Suppose I have these 2 tables:
Code:
And here I filled in some random data I filled in to make it more clear:
Code:
Now, my goal is to get all options one user voted in a poll separated by anything you like (I use ||). The problem is that I don't need the text of those votes (options), but the index of the option of a poll.
I have this query which select the option texts:
Code:
which returns
Code:
However, as you see, that returns E||F, but I want to have this:
Code:
Anyone a clue what I can do?
EDIT: I got the solution!
Here's the query for anyone who likes it:
Code:
Suppose I have these 2 tables:
Code:
poll_log:
log_id <- PK
poll_id
option_id
user_id
poll_option:
option_id <- PK
poll_id
option_text
And here I filled in some random data I filled in to make it more clear:
Code:
poll_log:
log_id (PK) | poll_id | option_id | user_id
------------|---------|-----------|--------
1 | 2 | 5 | 1
2 | 2 | 6 | 1
poll_option:
option_id (PK) | poll_id | option_text
---------------|---------|------------
1 | 1 | A
2 | 1 | B
3 | 1 | C
4 | 2 | D
5 | 2 | E
6 | 2 | F
Now, my goal is to get all options one user voted in a poll separated by anything you like (I use ||). The problem is that I don't need the text of those votes (options), but the index of the option of a poll.
I have this query which select the option texts:
Code:
SELECT l.poll_id, l.user_id,
GROUP_CONCAT(o.option_text SEPARATOR '||') as votes
FROM x_v2p5_xoopspoll_log l
JOIN x_v2p5_xoopspoll_option o
ON l.option_id = o.option_id
AND l.poll_id = o.poll_id
GROUP BY l.poll_id, l.user_id
which returns
Code:
poll_id | user_id | votes
--------|---------|------
2 | 1 | E||F
However, as you see, that returns E||F, but I want to have this:
Code:
poll_id | user_id | votes
--------|---------|------
2 | 1 | 1||2 <-- 1 and 2 because E is the second option of poll 2 and F is the third option of poll 3
Anyone a clue what I can do?
EDIT: I got the solution!
Here's the query for anyone who likes it:
Code:
SELECT poll_id, user_id, time, GROUP_CONCAT(vote_index) as votes
FROM (
SELECT l.poll_id, l.user_id, l.time, FIND_IN_SET(l.option_id, (
SELECT GROUP_CONCAT(o.option_id) FROM poll_option o WHERE o.poll_id = l.poll_id
)) - 1 AS vote_index
FROM poll_log l) t
GROUP BY poll_id, user_id