我有两个相同的SQL查询,我想合并结果。 第一个是:
SELECT USER.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST, USER, USER_PROFILE
WHERE FRIENDLIST.USER_ID=". $userID ."
AND APPROVED='YES'
AND USER.USER_ID=FRIENDLIST.USER_ID
AND USER.USER_ID=USER_PROFILE.USER_ID
第二个是:
SELECT USER.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST, USER, USER_PROFILE
WHERE FRIENDLIST.FRIEND_ID=". $userID ."
AND APPROVED='YES'
AND USER.USER_ID=FRIENDLIST.USER_ID
AND USER.USER_ID=USER_PROFILE.USER_ID
我尝试使用union但是我获得了一个空结果而不是$ userID = 2的2行。
SELECT USER.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST, USER, USER_PROFILE
WHERE FRIENDLIST.USER_ID=". $userID ."
AND APPROVED='YES'
AND USER.USER_ID=FRIENDLIST.USER_ID
AND USER.USER_ID=USER_PROFILE.USER_ID
UNION
SELECT USER.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST, USER, USER_PROFILE
WHERE FRIENDLIST.FRIEND_ID=". $userID ."
AND APPROVED='YES'
AND USER.USER_ID=FRIENDLIST.USER_ID
AND USER.USER_ID=USER_PROFILE.USER_ID
任何想法??
答案 0 :(得分:0)
我会像这样把它们结合起来:
SELECT USER.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST, USER, USER_PROFILE
WHERE (FRIENDLIST.USER_ID=". $userID ." or FRIENDLIST.FRIEND_ID=". $userID .")
AND APPROVED='YES'
AND USER.USER_ID=FRIENDLIST.USER_ID
AND USER.USER_ID=USER_PROFILE.USER_ID
嗯,严格来说并非如此。我会使用适当的连接语法并为表使用短别名:
SELECT u.USER_ID, NAME, SURNAME, EMAIL, STATUS, PHOTO
FROM FRIENDLIST f join
USER u
on u.USER_ID = f.USER_ID join
USER_PROFILE up
on u.USER_ID = up.USER_ID
WHERE (f.USER_ID=". $userID ." or f.FRIEND_ID=". $userID .") and
APPROVED='YES'
union
是做同样事情的另一种效率较低的方法。如果结果集为空,那是因为没有人符合条件。