I'm writing a query that display data from our issues
table. We have another table called labels
and a join table called issues_labels
. We usually assign an issue a label of 'High-Priority', 'Medium-Priority' or 'Low-Priority.
I'm unsure how to write my query so it would return this result:
Id | Title | Priority
2 everything is broken Low-Priority
4 internets is down High-Priority
I write queries all the time, but the simplicity (or not) of this one is driving me nuts. Do I need to write 3 sub-queries to pull issues that are linked to each label as so:
with hp_issues as (
SELECT *
FROM issues
INNER JOIN issues_labels on issues_labels.issue_id = issue.id
WHERE issues_labels.label_id = 10 --id for high priority issue
)
....
Any help appreciated.
Assuming issues_labels is a table that connects issues and labels in a many-to-many situation, you could do:
Example: http://sqlfiddle.com/#!15/b78ee/1
For any reason if one of your issues has more than one priority and you wanted it to be published as
5 | Some title | High Priority, Low Priority
you can do:
This is similar to MySQL's
group_concat()
Example for that is here: http://sqlfiddle.com/#!15/3dce4/2