我使用三個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
如果你不能做連接,你爲什麼不學習你在這裏有你需要的東西http://dev.mysql.com/doc/refman/5.1/en/join.html – cristian 2010-11-21 19:33:16