tags:

views:

424

answers:

2

I want to both fetch and use in a where clause the value returned from a sub-select in MySQL. Is this possible? It seems unecessary to write the sub-query out twice - however if I need to, will MySQL be clever enough to only run it one?

I have tried the following which does not work:

SELECT 
  (SELECT 1 FROM table WHERE somereallycomplicatedclause = 'something')
      AS subselectresult 
FROM content WHERE subselectresult = 1

This generates this error:

#1054 - Unknown column 'subselectresult' in 'where clause'

Thanks

+2  A: 

you can't use column aliases in a WHERE clause. try putting it in HAVING and it should work then.

Explanation here: http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

nickf
Great thanks - this works fine.
Tom Haigh
A: 

Your query as you displayed is strange. You can achieve the same result this way (cross product):

SELECT S.One
FROM contacts,
(SELECT DISTINCT 1 as One FROM table WHERE somereallycomplicatedclause = 'something') S

I think you should say more about what do you try to solve (e.g. what is the link between the sub query and the contacts table)?

Cătălin Pitiș
Sorry I oversimplified and also used the wrong table name. It is a table of content, the subselect returns whether the current Contact has access to parts of each row. So the subselect uses ContentId which is the primary key of the main table I am querying. There is probably a cleaner way of doing this but I am tied into an existing schema and the query ends up being much more complicated. The entire subselect SQL is generated by a different bit of code, otherwise I would have probably used a join.
Tom Haigh
What do you mean by subquery being generated by a different bit of code? My initial idea is to try to transform it in a join somehow (that's the reason for asking more details).
Cătălin Pitiș
I am not good in MySQL, but is it possible to define a function in MySQL that does the inner selection and returns the result? You could provide the parameters from the current row to the function and perform the selection.However, the performance will probably not change too much because, in principle, you have that inner select to be executed for each row resulted from the outer select.
Cătălin Pitiș