Search code examples
mysqlsqldatabaseticket-system

How can I get all comments for a single ticket in a ticket support system?


I have the following 2 tables (1 for the tickets and 1 for the ticket comments):

CREATE TABLE Tickets
(
ticket_id int(10)
ticket_business_id mediumint(8)
ticket_title varchar(50)
ticket_message varchar(1000)
ticket_is_active tinyint(1)
ticket_created_date datetime
ticket_latest_comment_date datetime
)

CREATE TABLE TicketComments
(
comment_id int(11)
ticket_id int(11)
business_id mediumint(8)
message varchar(1000)
created_date datetime
support_worker_id tinyint(1)
)

In my system, a user can get help by creating a support "ticket". In this ticket there is a subject and a message. After it is created, both the user and one of the support workers that are there to help them can comment on the ticket. I would like to know how I can get all of the comments relating to the ticket. At first I thought it would be as simple as the following query but then I realized the original ticket has the first message that should be considered a comment also (ticket_message). This means I need to retrieve ticket_message from Tickets table and all message from TicketComments.

SELECT * 
FROM Tickets, TicketComments 
WHERE Tickets.ticket_business_id= TicketComments.business_id

Solution

  • If you know the ticket ID you could get the message of the ticket and all the comments related to it e.g. through a union:

    SELECT ticket_message FROM Tickets WHERE ticket_id=?ticketId
    UNION
    SELECT message FROM TicketComments WHERE ticket_id=?ticketId