简体   繁体   中英

I want to combine two columns into a new column, but only if one isn't blank, and then sort by that new column. (MySQL)

Let's say I have two columns, city and sitename.

City        Sitename
Boston      Hynes Convention Center 
Baltimore   The Sheraton 
NYC         Times Square
            Applebees 
Tuoson       
Beijing     
            My Backyard

I've purposefully left some fields in either column blank, and here's why. When I output this information using PHP, I want it to come out in the form {city} - {sitename}, but ONLY if they're both not blank. If either one is blank, then I just want it to show {city} or {state}, whichever it is. Then, once I have this new column of combined (or not) values, I want to sort my data by this new column A - Z. So in the end it should appear something like this...

City         Sitename                  Combined
             Applebees                 Applebees
Baltimore    The Sheraton              Baltimore - The Sheraton
Beijing                                Beijing
Boston       Hynes Convention Center   Baltimore - Hynes Convention Center
             My Backyard               My Backyard
NYC          Times Square              NYC - Times Square
Tuoson                                 Tuoson

I've combined and renamed columns and done sorting before, but trying add in the conditions and cases is having me scratching my head.

Oh and this isn't a table alteration, it's how I want to retrieve the data. So the statement should be something like...

"SELECT * FROM table... "

This is untested, I apologize.

Select Trim(BOTH ' - ' From Concat(Coalesce(city, ''), ' - ', Coalesce(sitename, ''))) As citysite
From my_table
Order By citysite

I believe MySQL lets you order by an aliased column. If that's not the case, then simply copy the Trim() contents into the Order By as well.

SELECT 
   COALESCE(City,'') as City, 
   COALESCE(Sitename,'') AS Sitename, 
   CASE 
     WHEN COALESCE(City,'')='' THEN Sitename
     WHEN COALESCE(City,'')<>'' AND COALESCE(Sitename,'')='' THEN City
     ELSE City + ' - ' + Sitename 
   END AS Combined
FROM table
ORDER BY 
 CASE 
  WHEN COALESCE(City,'')='' THEN Sitename
  WHEN COALESCE(City,'')<>'' AND COALESCE(Sitename,'')='' THEN City
  ELSE City + ' - ' + Sitename 
 END

It should be pretty straight forward.

SELECT case when city is null then
           sitename
       else
           city || ' - ' || sitename
       end 
FROM table

?

select  City + ' ' + Sitename   
where City ....
  and Sitename ...
order by City + ' ' + Sitename   

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