I’m designing a ticket system in PHP/MySQL.
Each ticket represents one row in the ‘tickets’ table.
Users can add multiple ‘comments’ to each ticket.
When viewing a ticket I just do an SQL query on the ‘comments’ table to select all comments linked to the corresponsing ticketid
However, now I have to design a search page, which returns any matching tickets and immediately show (part of, e.g. last 5) their linked comments.
I have this working by performing the same SQL query I use in the single ticket view page, but repeating this for every matching row in the search query. So if you have 1500 matching rows, that means 1500 SQL queries on the ‘comments’ table, yes, not very efficient…
Now I was wondering: Is there a way to join the comments table to the tickets table, but have multiple rows from the comments table ‘squeezed’ into one column?
I was thinking about doing a CONCAT() on the comments rows, returning them as comma-seperated values, which I could then explode() again in php to get an array containing all my comments for each ticket. But is this the most effective way or is there something better?
EDIT: Keep in mind that tickets which don’t have any comments yet should also we returned by the query
Zane Bien answered the
CONCATquestion, I won’t comment it because there is not much to add, but you also asked if it is the most effective way so I’ll go for this one.I really don’t like the
CONCATsolution. It’s not the philosophy of SQL and you never know what users will write in the comment area.As far as SQL is concerned, the right way of doing it is:
Then in PHP you simply iterate over the resultset and build the output. Note that the LEFT JOIN will rightfully return tickets without comments.
If you feel a bit uneasy – but should not ! – having the ticket information on each line you can split the query in 2:
And
That implies some more work on the application side as you’ll have to link back the comments to the ticket.
My advice: go for the all-in-one query.