2

I'm trying to get an one line output for each row my statements iterates to but it outputs like 100 times for every "ticket" it finds. In the current SQL Queue there are only 4 possible tickets which match the criteria.

$ticketIdQuery = pg_query($db, "SELECT ticket.assignee_id, ticket.subject FROM ticket INNER JOIN ticket_assignee_mapping ON ticket.assignee_id=ticket_assignee_mapping.assignee_id WHERE status_id = $firstLevelId");

if($ticketIdQuery)
{
    while ($ticketIdQueryFetch = pg_fetch_array($ticketIdQuery))
    {
        print_r($ticketIdQueryFetch);
    }
}

Is there a way to limit the output to one for each row it finds

1
  • 1
    Hi Dnz, welcome to Stack Overflow. The reason for getting all of the records for each row as you put it, is due to the join in your SQL. You could try using a DISTINCT clause in your where such that you only get the distinct returned. Commented Feb 25, 2020 at 14:50

1 Answer 1

1

When your JOINed tables have one-to-many relationships and you only select a limited number of columns, you can't see why you are getting so many results. So rather than use DISTINCT, I suggest using a GROUP BY clause in order to specify the columns you're actually interested in. If you also add a COUNT(*) to your SELECT, you can keep tweaking your query until the record count totals 1 for each row returned. Try this:

$ticketIdQuery = pg_query($db, "SELECT ticket.assignee_id, ticket.subject, COUNT(*) FROM ticket INNER JOIN ticket_assignee_mapping ON ticket.assignee_id=ticket_assignee_mapping.assignee_id WHERE status_id = $firstLevelId GROUP BY ticket.assignee_id, ticket.subject");

If you still have questions, please post the table definitions for ticket and ticket_assignee_mapping.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.