简体   繁体   中英

Two queries, merge results, sort

I am new at this and stuck for days...trying everything I could find from Google and these Forums.

I have one MySQL table that I need to pull data from.

I need to pull all records where AgentID = 1234 Also, pull all records where OfficeID = 4321 (and AgentID != 1234 to prevent dupes) Then display the results with AgentID records first, if they exist, then the OfficeID records.

I tried a UNION, but could not find a way to sort or show Agent first, Office second. Tried array_merge and two queries/results, but the merged data was mixed instead of Agent First data, again, with no way to sort by Agent first.

Any ideas would be greatly appreciated!

Bill

You can use a CASE statement in the ORDER BY to impose your specified conditions.

SELECT *
    FROM YourTable
    WHERE AgentID = 1234
        OR (OfficeID = 4321 AND AgentID <> 1234)
    ORDER BY CASE WHEN AgentId = 1234 THEN 0 ELSE 1 END,
             AgentID, OfficeID

Try like this:

( SELECT 1 AS batch_no, .... FROM .... ) # the query with AgentID - the one that you want displayed first
 UNION
( SELECT 2 AS batch_no, .... FROM .... ) 

ORDER BY batch_no

Try something like:

SELECT * FROM table 
WHERE AgentId = 1234 OR (OfficeId = 4321 AND AgentId != 1234)
ORDER BY CASE WHEN AgentId = 1234 THEN 0 ELSE 1 END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM