Bill Bill - 9 months ago 38
MySQL Question

Combining the data in two columns into one for sorting

I am trying to UNION two columns in a SELECT, and alias to a third.

I also need to retrieve the data matching the WHERE clause, then sort by the aliased column (MLS_SORT).

This, and variations of it that I have tried, don't work.

SELECT *
FROM
(SELECT MLS_AGENT_ID AS MLS_SORT FROM mlsdata)

UNION

(SELECT MLS_OFFICE_ID AS MLS_SORT FROM mlsdata)

WHERE (MLS_AGENT_ID = $agent_narid) OR (MLS_OFFICE_ID = $office_narid)

ORDER BY MLS_SORT


This part does work and creates the MLS_SORT alias with the correct values, but I can't figure out how to limit the results to the WHERE clause above:

(SELECT MLS_AGENT_ID AS MLS_SORT FROM mlsdata)

UNION

(SELECT MLS_OFFICE_ID AS MLS_SORT FROM mlsdata)


Am I at least going down the correct path or is this not the proper way to proceed?

Thanks for any assistance.

Answer Source

The trick is to understand the syntax of UNION: query UNION query

I think you want:

SELECT MLS_SORT
FROM
(
    SELECT MLS_AGENT_ID AS MLS_SORT 
      FROM mlsdata
     WHERE MLS_AGENT_ID = $agent_narid

    UNION

    SELECT MLS_OFFICE_ID AS MLS_SORT 
      FROM mlsdata
     WHERE MLS_OFFICE_ID = $office_narid
)
ORDER BY MLS_SORT

To get the two ID subsets into a single result set then sort them.

But, this whole query looks like it's going to give a two-row result set -- one row for an agent and another for an office. Is that what you want?

Your logic effectively typecasts agent id and office id numbers into a single result set. Does that make sense in your application?