我有一个存储朋友的表,如下所示:
CREATE TABLE `friends` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`to_id` int(11) NOT NULL,
`from_id` int(11) NOT NULL,
`status` char(10) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
INSERT INTO `friends` (`id`, `to_id`, `from_id`, `status`, `created_at`, `updated_at`) VALUES
(1, 2, 3, 'pending', '2013-08-10 00:00:00', '2013-08-10 00:00:00'),
(2, 1, 3, 'approved', '2013-08-11 00:00:00', '2013-08-11 00:00:00'),
(3, 2, 1, 'approved', '2013-08-15 20:51:20', '2013-08-15 20:51:20');
我希望能够确定一个成员(我们将调用查看器)是否是另一个成员(他们正在查看的个人资料)的朋友的朋友。我需要此信息来确定是否允许查看者查看个人资料。假设我(id 为 2)正在查看 id 为 3 的配置文件。下面的查询是我目前所拥有的。
SELECT COUNT(*) FROM profiles
LEFT JOIN friends ON (profiles.id = friends.to_id OR profiles.id = friends.from_id)
WHERE (friends.to_id = 2) OR (friends.from_id = 2)
AND profiles.id IN (
SELECT profiles.id
FROM profiles
LEFT JOIN friends ON (profiles.id = friends.to_id OR profiles.id = friends.from_id)
WHERE (friends.to_id = 3) OR (friends.from_id = 3)
GROUP BY profiles.id
)
AND friends.status = 'approved';
当我在 PHPMyAdmin 中运行它时,我得到 4,但我不应该得到 1,因为还有 1 个我们都是朋友的其他成员吗?一旦我在我的模型中运行它,我就会确保如果返回的行数超过 0 行,那么我可以查看配置文件。任何人都可以帮助调整它以使其正常运行吗?在这一点上,我有点迷失了。提前致谢。
我能够弄清楚,这是下面的工作查询:
SELECT COUNT(*) AS count
FROM profiles
WHERE profiles.id IN (
SELECT profiles.id
FROM profiles
LEFT JOIN friends ON (friends.to_id = profiles.id OR friends.from_id = profiles.id)
WHERE (friends.to_id = 1 OR friends.from_id = 1)
AND profiles.id != 1
)
AND profiles.id IN (
SELECT profiles.id
FROM profiles
LEFT JOIN friends ON (friends.to_id = profiles.id OR friends.from_id = profiles.id)
WHERE (friends.to_id = 3 OR friends.from_id = 3)
AND profiles.id != 3
)