Two queries, merge results, sort

Hi all,

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

What format are you trying to display these results in?

What went wrong with doing two queries with two sets of results?

Try this:

SELECT *, IF(AgentID = 1234, 1, 2) AS AgentsFirst FROM AgentsTable WHERE AgentID = 1234 OR OfficeID  =  4321 ORDER BY AgentsFirst

Just to clarify: we’re using the IF() function, to add extra column that will have value 1 or 2 for each record in the recordset. Then we use this column to sort records, so that records with AgentID = 1234 are displayed first.

phphelp

That worked perfectly! Thank you so much!

I can’t believe how much I was trying over-complicate it.

And thank you jSherz for replying…I tested the code before I replied.

Sponsor our Newsletter | Privacy Policy | Terms of Service