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

只愿长相守 提交于 2019-12-12 03:52:43

问题


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               Alester@lam.com Alester@lam.com  Alester@lam.com
Friend_E_Mail           jude@lam.com    carl@lam.com   jones@lam.com

Desired Output if ("?" in above query is: jones@lam.com)

+--------------+-----------+------------+
|Member        |E_Mail     |  Name      |
+---------------------------------------+
 Alester A   Alester@lam.com  Alester

Desired Output if("?" in above query is: Alester@lam.com)

+--------------+-----------+------------+
|Member        |E_Mail     |  Name      |
+---------------------------------------+
 Jude B        jude@lam.com  Jude
 carl C        carl@lam.com  Carl
 Jones J       jones@lam.com 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.


回答1:


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.



来源:https://stackoverflow.com/questions/16551944/union-operation-not-allowed-in-sub-query-is-there-a-way-to-fix-this-in-one-sin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!