Jump to content

Problem with Union not returning the specified column


Recommended Posts

I'm trying to merge two queries (as from what I understand this is faster than if it were to be 2 separate queries - correct me if I'm wrong).

 

It's a table which stores website pages with both parent and child pages. There's an ID (parent_id) specified for child pages of who its parent is, but I need a second query in order to lookup the ID of its parent and determine what its parents URL (page_url) is.

 

My query at the moment doesn't return parent_url where I've specified it to right after the UNION. What am I doing wrong?

 

SELECT *, page_url, parent_id AS get_parent_id FROM pages WHERE page_url='$page' AND child='1'
UNION 
SELECT *, page_url AS parent_url, parent_id FROM pages WHERE id='get_parent_id'

[*]I'm selecting all columns as I wish to return every column for the first query, and just the page_url of its parent for the second query. From my understanding and experience you have to select the exact same columns with both queries or the UNION will break and the code will through up a MySQL error.

[*]It's the same table, so its the same amount of columns.

[*]There is no MySQL error, just the second SELECT query isn't returning the page_url column AS parent_url which is what I desire.

Try:

 

SELECT *, page_url AS parent_url, parent_id FROM pages WHERE id='get_parent_id
UNION
SELECT *, page_url, parent_id AS get_parent_id FROM pages WHERE page_url='$page' AND child='1'

 

I've simply reversed them.

 

UNION "honors" the "first" SELECT expression for the resulting attributes names of the result.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.