Question

been a long time reader so thanks for all the help thus far and sorry if I make any noob mistakes creating this question!

I am trying to build a query that is already quite complex (for me anyway) and I need to have one of the fields for each row be a single result from another query using a field from the main query as it's WHERE statement.

I have tried using variables but it seems you cant set these after the main select, makes sense I guess but at the time I was thinking of the select as working like a foreach loop as it collects the rows.

It would take a very long time to explain the whole structure of the databases (the tables are provided to me and need to stay how they are) but I will try and capture the query structure with the following example.

Select

a.field1,
a.field2,
b.field1,
b.field2,
c.field3,
c.field3,
( select aa.field1 from zz inner join aa on zz.field2 = aa.field3 where zz.field3 = a.field1) as field7

FROM
All the tables and joins
WHERE {some stuff}

Bottom line is that the main query works in isolation perfectly and the sub query also works fine on it's own when I feed it a faked a.field1 value

But together the query runs but just returns NULL for the field7 column.

I started out with trying to set a variable to the a.field1 value just after the ( for the sub query but this just causes intellisense to go nuts on all the table names above.

Any pointers would be much appreciated!

Was it helpful?

Solution

AFAIK, you can't use them directly.

Your options are repeating the subselect:

Select
a.field1,
a.field2,
b.field1,
b.field2,
c.field3,
c.field3,
( select aa.field1 from zz inner join aa on zz.field2 = aa.field3 where zz.field3 = a.field1) as field7

FROM
All the tables and joins
WHERE 
( select aa.field1 from zz inner join aa on zz.field2 = aa.field3 where zz.field3 = a.field1) = somevalue;

Or making everything a sub select:

select result.* from
(Select
    a.field1,
    a.field2,
    b.field1,
    b.field2,
    c.field3,
    c.field3,
    ( select aa.field1 from zz inner join aa on zz.field2 = aa.field3 where zz.field3 = a.field1) as field7

    FROM
    All the tables and joins
    WHERE {some stuff}) as result
where result.field7 = somevalue

OTHER TIPS

Would this do it?

Select a.field1,
    a.field2,
    b.field1,
    b.field2,
    c.field3,
    c.field3,
    aa.Field1 as field7

FROM All the tables and joins
LEFT JOIN ( select aa.field1,
                   zz.Field3
            from zz inner join aa on zz.field2 = aa.field3) aa
ON aa.field3 = a.field1 
WHERE {some stuff}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top