0

我有两个相同的 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

我尝试使用联合,但我得到一个空结果而不是 $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

有任何想法吗??

4

1 回答 1

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是另一种效率较低的方法来做同样的事情。如果结果集为空,那是因为没有人符合条件。

于 2013-03-03T19:46:37.163 回答