3

When you have a table you can limit the amount of results. But I have two tables:

This is the first one:

$requests_q = mysql_query("SELECT ava_users.*
FROM ava_friend_requests
LEFT JOIN ava_users 
ON ava_friend_requests.from_user = ava_users.id
WHERE ava_friend_requests.to_user = $user[id]");

This is the second one:

$friends_q = mysql_query("SELECT ava_users.*
FROM ava_friends
LEFT JOIN ava_users 
ON ava_friends.user2 = ava_users.id
WHERE ava_friends.user1 = $user[id]");

This is the table definition for ava_friend_requests:

Field       Type                    Null    Key     Default     Extra
id          int(11) unsigned        NO      PRI     NULL        auto_increment
from_user   int(11)                 YES     MUL     NULL    
to_user     int(11)                 YES     MUL     NULL    

This is the table definition for ava_friends:

Field   Type    Null    Key     Default     Extra
user1   int(11) NO      MUL     NULL    
user2   int(11) NO      MUL     NULL

I'd like to limit the results in a way as if there was no second query (i.e. two queries but ONE LIMITED RESULT ONLY). I was searching the net but couldn't find anything so far. I'm not sure if UNION can help me in this case.

4

1 回答 1

3

尝试这样的事情:

$union_q = mysql_query(
    "SELECT ava_users.*
     FROM ava_friend_requests
     LEFT JOIN ava_users 
     ON ava_friend_requests.from_user = ava_users.id
     WHERE ava_friend_requests.to_user = $user[id]
     UNION ALL
     SELECT ava_users.*
     FROM ava_friends
     LEFT JOIN ava_users 
     ON ava_friends.user2 = ava_users.id
     WHERE ava_friends.user1 = $user[id]
     LIMIT 0, 10");

更新:正如 Sylvain Leroux 在评论中所指出的,联合返回的结果顺序不能保证是第一个查询中的所有结果,然后是第二个查询中的所有行。如果这对您来说是个问题,建议修改查询以对记录进行排序,例如如下:

SELECT ava_users.*, 0 AS ord
FROM ava_friend_requests
LEFT JOIN ava_users 
ON ava_friend_requests.from_user = ava_users.id
WHERE ava_friend_requests.to_user = $user[id]
UNION ALL
SELECT ava_users.*, 1 AS ord
FROM ava_friends
LEFT JOIN ava_users 
ON ava_friends.user2 = ava_users.id
WHERE ava_friends.user1 = $user[id]
ORDER BY ord
LIMIT 0, 10

(如果您不想ord在 SELECT 中包含该字段,可以通过将整个事情变成一个子查询,但这会使其更加复杂,并且可能超出原始问题的范围。)

于 2013-08-08T19:07:16.263 回答