Search code examples
mysqlnode.jsnode-mysql

Can I filter my results with a WHERE clause based on the result from a subquery in MySQL?


This is my current mysql query.

    SELECT t.id, t.customer, t.indicator_tag, t.indicator_manu, t.indicator_model, t.created_at, t.updated_at, 
    ( SELECT status FROM events WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) AS status, 
    ( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.created_by ) AS created_by, 
    ( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.updated_by ) AS updated_by 
    FROM tickets t 
    WHERE status = 'Pending' OR status = 'Diagnosed' OR status = 'Repaired' 
    ORDER BY t.customer ASC, status ASC, t.indicator_tag ASC;

The WHERE clause in the above statement does not throw any errors, but it also does not filter anything either. I am still fairly new to SQL so I haven't delved too deeply into JOINS yet. I should also note that the events table will have multiple events for each ticket, and that the sub-query on line 2 will just grab the newest one. Is there a way to filter the results based on data from another table but while only grabbing the newest event for each ticket?

To put it another way:
TABLE tickets HAS MANY events
events BELONG to ticket

HTML Output Example

The example above will show the output that I get. Note that it shows merely the newest status rather than all of the events like it would on the single ticket page. If I could provide more information I would be happy to oblige.


Solution

  • Use HAVING:

    SELECT t.id, t.customer, t.indicator_tag, t.indicator_manu, t.indicator_model, t.created_at, t.updated_at, 
        ( SELECT status FROM events WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) AS status, 
        ( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.created_by ) AS created_by, 
        ( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.updated_by ) AS updated_by 
    FROM tickets t 
    HAVING status = 'Pending' OR status = 'Diagnosed' OR status = 'Repaired' 
    ORDER BY t.customer ASC, status ASC, t.indicator_tag ASC;
    

    http://www.w3schools.com/sql/sql_having.asp

    From the docs:

    A HAVING clause can refer to any column or alias named in a select_expr in the SELECT list or in outer subqueries.