I’m having some trouble with finalizing my MySQL query. Imagine that i combine the tables tickets, invoice line and users. Each ticket has one or more invoice lines and each user can have one or more tickets.
I’m trying to create a query which I can use to create the name badges. For this badge I need to know the name and the items the person registered for.
I created the following MySQL query
SELECT u.firstName, u.lastName, il.invID, il.name,
CASE
WHEN il.name = 'Conference Dinner'
THEN 'Diner'
END AS 'conference_dinner',
CASE
WHEN il.name = 'Regular Conference Fee' THEN 'Conference'
WHEN il.name = 'Conference Fee for Phd. Students' THEN 'Conference'
END AS 'conference',
CASE
WHEN il.name = 'Pre-Conference Fee' THEN 'Pre-Conference'
END AS 'pre_conference',
FROM invoice_line il, events_tickets et, users u
WHERE il.invID = et.invID
AND et.userID = u.ID
The query is almost fine, however it produces for a user with three invoice lines (= three items) three lines in the table, and I’d like these three lines to merge to one line. A Group By on the users ID will result in one line, but than the case created columns won’t be merged into the one line, only one of them is displayed.
I might have used the wrong way of doing this. But It should result in an table like this:
firstName | lastName | conference_diner | conference | pre_conference |
----------------------------------------------------------------------
John | Doe | Diner | Conference | |
Jane | Norman | | Conference | Pre-Conference |
Martijn | Thomas | | Conference | |
Pete | Johns | | | Pre-Conference |
Currently this results in:
firstName | lastName | conference_diner | conference | pre_conference |
----------------------------------------------------------------------
John | Doe | Diner | | |
John | Doe | | Conference | |
Jane | Norman | | Conference | |
Jane | Norman | | | Pre-Conference |
Martijn | Thomas | | Conference | |
Pete | Johns | | | Pre-Conference |
Thanks in advance
You might try something along these lines:
A comparison in mysql results in a number, 0 for false and 1 for true. So you can simply sum those up to count the lines matching a given expression. In other words, all the lines from the join which belong to a single user are grouped, those matching a certain property are counted, and these counts will decide what to print as the aggregate value for that user in the resulting table.