2010-11-21 140 views
0

我使用三个MySQL表,看起来像:Mysql的加入三个表问题

会员表占

|  id  |  name | status | 
------------------------------------------- 
|  1  |  mike |  0  | 
|  2  |  peter |  1  | 
|  3  |  john |  1  | 
|  4  |  any |  1  | 

该表的好友列表:

| myid  | user  | date | 
------------------------------------------ 
|  10  |  2  | 2010-01-04 | 
|  3  |  10  | 2010-09-05 | 
|  4  |  10  | 2010-10-23 | 

的用户画廊列表:

| fotoid  | userid  | pic1 | 
------------------------------------------ 
|  101  |  2  | 1.jpg | 
|  102  |  3  | 2.jpg | 
|  103  |  4  | 3.jpg | 

我想加入这三个表并获得查询结果,该结果将列出我添加到朋友列表中的用户以及那些让我同时添加到列表中的用户,所有这些用户都必须具有状态'1'成员表格并显示来自图库表格的照片。

在这个例子中,我的ID是'10'。在画廊字段表中,“MyID”表示已将其他用户添加到他们的朋友的用户,而“用户”是添加的用户的ID。

最终结果在这个例子应该是这样的:

| id | name | status | pic1 | 
------------------------------------------------ 
| 2  | peter |  1  | 1.jpg | 
| 3  | john |  1  | 2.jpg | 
| 4  | any  |  1  | 3.jpg | 

我怎么能这样做?

MySQL的EXPLAIN:

id | select_type  | table | type | possible_keys | key | key_len | ref | rows | extra        
------------------------------------------------------------------------------------------------------------------------------------------------- 
1 | primary   | g  | ALL  | id    | NULL | NULL  | NULL | 7925 | Using where 
1 | primary   | a  | eg_ref | id    | id  | 4   | g.id | 1  | Using where 
2 |DEPENDENT SUBQUERY| a2 | index | id    | NULL | NULL  | NULL | 90734 | Using index; Using temporary; Using filesort; 
2 |DEPENDENT SUBQUERY| f  | index | rds_index  |rds_index| 8   | NULL | 138945 | Using where;Using index;Using join buffer 
+0

如果你不能做连接,你为什么不学习你在这里有你需要的东西http://dev.mysql.com/doc/refman/5.1/en/join.html – cristian 2010-11-21 19:33:16

回答

2
SELECT a.id, 
     a.name, 
     a.status, 
     g.pic1 
FROM accounts a 
     JOIN galleries g 
     ON g.userid = a.id 
WHERE a.id IN (SELECT a2.id 
       FROM accounts a2 
         JOIN friends f 
         ON (f.myid = a2.id 
           OR f.user = a2.id) 
       WHERE (f.myid = 10 
          OR f.user = 10) 
       GROUP BY a2.id) 
     and a.status = 1 

编辑1

让我们对于现在的子查询,现在通过东西松动组:

请确保您有索引上这些列:

accounts.id 
friends.myid 
friends.user 

并运行此查询:

SELECT a2.id 
FROM accounts a2 
     JOIN friends f 
     ON f.myid = a2.id 
WHERE f.user = 10 
UNION ALL 
SELECT a2.id 
FROM accounts a2 
     JOIN friends f 
     ON f.user = a2.id 
WHERE f.myid = 10 

然后回来后长期执行的如何。

+0

@ Pentium10 - 谢谢Pentium10。我试过这个查询,但它需要超过5分钟,并且mysql服务器卡住了。有什么理由? – Sergio 2010-11-21 20:31:18

+0

向我们展示您的表格架构,可能您缺少关键列上的一些索引。在查询上运行'explain extended'并发布详细信息。 – Pentium10 2010-11-21 20:43:52

+0

@ Pentium10 - 你可以在我的问题中看到来自mysql的详细解释。我只是发布这些细节。谢谢。 – Sergio 2010-11-21 22:15:50