prw Posted July 11, 2011 Share Posted July 11, 2011 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' Quote Link to comment Share on other sites More sharing options...
AyKay47 Posted July 11, 2011 Share Posted July 11, 2011 1. you are selecting *, then specific fields...one or the other. 2. Do both of your tables have the same count of fields..? 3. what error(s) do you receive? Quote Link to comment Share on other sites More sharing options...
prw Posted July 11, 2011 Author Share Posted July 11, 2011 [*]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. Quote Link to comment Share on other sites More sharing options...
ebmigue Posted July 13, 2011 Share Posted July 13, 2011 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.