过滤表然后加入结果

时间:2010-09-02 02:14:29

标签: mysql

我正在尝试按ID过滤表集合,然后加入users.user_id上的collections.user_id。

这是我试过的查询

SELECT * FROM 
 (SELECT * FROM collections WHERE mid=`$id`) c 
 JOIN users on c.mid = users.user_id ORDER BY users.user_id

显然没有成功。任何帮助或指示将不胜感激!

CREATE TABLE `collections` (
  `user_id` int(11) NOT NULL,
  `mid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `api_public` varchar(32) DEFAULT NULL,
  `api_secret` varchar(32) NOT NULL,
  UNIQUE KEY `unique id` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

2 个答案:

答案 0 :(得分:4)

你能试试吗?

SELECT * 
  FROM  collections A 
  JOIN users B ON A.mid = B.user_id 
              AND A.mid = 'value of $id'
ORDER BY B.user_id 

答案 1 :(得分:2)

这个怎么样:

SELECT c.*, u.* FROM collections c
JOIN users u ON c.mid = ? AND c.mid = u.user_id
ORDER BY u.user_id

(当然?是参数标记)。