Reputation: 57
I'm writing a ticket program in vb.net using MySQL.
What I want is to use the Statename that a ticket can have (open/closed/on hold/etc) that I get from query 1, and use it in query 2 to get a list of all statenames, with the result of the first query as first item.
I now use 2 queries after each other, but i'm sure it can be done in 1 query.
Query 1:
SELECT StateName
FROM Tickets t
JOIN States s
ON s.stateID = t.StateID
WHERE TicketNumber = & *intTicketNumber*
--> Result = "Open"
Query 2:
SELECT StateName
from States
ORDER
BY(case when StateName = '" & *StrStateName* & "' then 0 else 1 end)
, StateName desc
The Desired result of the combined query should be:
How Can I combine there 2 queries? Any help would really be appreciated!
Upvotes: 0
Views: 39
Reputation: 28834
States
as your Leftmost table and do a LEFT JOIN
to the Tickets table, on stateID
and TicketNumber
. Match the TicketNumber
in the Join condition, instead of Where
.States
as leftmost table will ensure that all the StateName values will be considered.t.StateId
will be NULL
(post LEFT JOINing), except for one StateName (assigned to the Ticket currently).t.StateId
in Descending order. Ticket's current StateName will appear first in the list and rest of them sorted afterwards.Try with Left join instead:
SELECT s.StateName
FROM States AS s
LEFT JOIN Tickets AS t
ON s.stateID = t.StateID AND
t.TicketNumber = $intTicketNumber -- $intTicketNumber is the input variable
ORDER BY t.StateID DESC,
s.StateName DESC
Upvotes: 2