Search code examples
sqlsubqueryunionjetms-access-2000

"Union Operation not allowed in sub query" is there a way to fix this in one single query?


This Query Dose NOT work in Access 2000

SELECT (Members.First_Name + " " + Members.Last_Name)AS Member,
(SELECT Friend_E_Mail,
FROM    Friends,Members WHERE My_E_Mail = ? and Friend_E_Mail <> ?
UNION ALL
SELECT My_E_Mail,FROM  Friends,Members 
WHERE  Friend_E_Mail = ?and My_E_Mail <> ?) AS  E_Mail ,
(Members.First_Name) AS Name

FROM Members,Friends

Sample Tables

Members(all VARCHAR)     SOME DATA
First_Name               Alester Jude Carl Jones
Last_Name                A       B    C    J

FRIENDS(ALL VARCHAR)
My_E_Mail               [email protected] [email protected]  [email protected]
Friend_E_Mail           [email protected]    [email protected]   [email protected]

Desired Output if ("?" in above query is: [email protected])

+--------------+-----------+------------+
|Member        |E_Mail     |  Name      |
+---------------------------------------+
 Alester A   [email protected]  Alester

Desired Output if("?" in above query is: [email protected])

+--------------+-----------+------------+
|Member        |E_Mail     |  Name      |
+---------------------------------------+
 Jude B        [email protected]  Jude
 carl C        [email protected]  Carl
 Jones J       [email protected] Jones

PS the "?" are query string parameters that im passing in the "?" i know that works fine.

MY QUESTION IS : i keep getting this error "Operation Not Allowed in Sub Query"

is their a work around query i can use without using a stored procedure or using multiple queries since this needs to be ONE SINGLE QUERY!?

Thanks.


Solution

  • You can´t return more then 1 row in a select subquery. To this case you have to use the CASE expression.

    You have to do something like this:

    SELECT (m.First_Name + " " + m.Last_Name) AS Member,
           case 
           when f1.my_email is null 
            then f2.my_e_mail
            else f1.friend_email 
           end as email,
           m.First_Name AS Name
    from members m
    left outer join friends f1
      on m.email = f1.my_e_mail
      and f1.friend_e_mail = ?
    left outer join friends f2
      on m.email = f2.friend_e_mail
      and f2.my_e_mail = ?;
    

    Thys way it will return a row for each friend. You can see that the names of the fields are not so good, try to refactory it. my_e_mais isn´t so representative.