0

I have table A whit this columns:

id   name      to_include
1    wanted1   null
2    wanted2   wanted1

If the query is for wanted2 then I need a way to use the value from to_include column (in this case wanted1) in the WHERE clause I have tried some like this:

SELECT * FROM (
    SELECT * FROM A WHERE name = 'wanted2'
) AS B
UNION
SELECT * FROM A WHERE A.name = B.to_include

That got this error: Unknown column 'B.to_include' in 'where clause

Expected result: A recordset with both two rows from the example table.

7
  • You want to use either a JOIN or IN or EXISTS not a UNION Commented Apr 29, 2017 at 20:57
  • I think both is needed - UNION and JOIN. But the question isn't really clear. Commented Apr 29, 2017 at 20:57
  • Post what the result should look like, it's hard to tell from your description. I suspect @PaulSpiegel is right -- you need a JOIN in one query and then combine that with UNION. Commented Apr 29, 2017 at 20:58
  • Expected result: A recordset with both two rows from the example table. Commented Apr 29, 2017 at 20:59
  • 1
    Then you should be fine with Barmars answer. I was afraid, you would need to "include" the rows recursively. Commented Apr 29, 2017 at 21:07

1 Answer 1

3

You can't refer to a previous query in a UNION as an alias. Each query in the UNION is processed independently, then the results are combined.

The second query in the UNION needs to be a JOIN, and you need to repeat the criteria from the first query when you do this.

SELECT * 
FROM yourTable WHERE name = 'wanted2'

UNION

SELECT b.*
FROM yourTable AS a
JOIN yourTable AS b ON b.name = a.to_include
WHERE a.name = 'wanted2'

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

Depending on data it's also possible to use only the second part with ON b.name IN (a.name, a.to_include)
@PaulSpiegel Yeah, that works, but this code expresses the intent more clearly, IMHO.
@PaulSpiegel I have tested your version and yes that work also, but what you mean with "Depending on data"?
@MTK If name is not UNIQUE you might get a different result (creating duplicates). Here's an exmple: sqlfiddle.com/#!9/02820/1
@PaulSpigel. Thank's. Is good for me to know that. I try to learn by little steps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.