How do you query something like

if parent = 0 then alias is network_id else alias is group_id

Is this possible with only queries?

  • Do you want to show a different column alias based on a condition?
    – siride
    Dec 27 '13 at 2:12
  • @siride yes, display different column aliases based on specified conditions. where the data remains the same.
    – madziikoy
    Dec 27 '13 at 2:18

It's impossible to do what you want, and if not impossible, not a good idea. The columns in a resultset belong to every row in the resultset. You can't have a different alias for each row. That wouldn't make sense. Imagine a table in a spreadsheet that had a column header for each column and for each row. How would you even notate that?

It seems, though, that you want to be able to consider some upstream column to be a network_id in some cases and a group_id in others. I won't question your schema or query design, though it is suspect. If it's reasonable, then you can easily achieve this by simply having two columns: network_id and group_id. Only fill in network_id if parent = 0, and only fill in group_id if parent is not 0, like so (using standard SQL):

CASE WHEN parent = 0 THEN alias ELSE NULL END AS network_id,
CASE WHEN parent <> 0 THEN alias ELSE NULL END AS group_id,

Your application code can use whichever column needs to be used.

  • Exactly what I needed. Just added an unset function with php to get rid of the null columns.
    – madziikoy
    Dec 27 '13 at 2:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.