CREATE TABLE IF NOT EXISTS `users` (
`idu` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`idu`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`idu`, `name`) VALUES (1, 'a'),(2, 'b'),(3, 'c'),(4, 'd'),(5, 'f'),(6, 'g'),(7, 'k');
CREATE TABLE IF NOT EXISTS `banned` (
`idu` int(11) NOT NULL,
`idb` int(11) NOT NULL,
PRIMARY KEY (`idu`,`idb`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Дамп данных таблицы `banned`
--
INSERT INTO `banned` (`idu`, `idb`) VALUES (2, 3),(3, 4),(3, 5),(4, 2);
-- Запрос
SELECT u.idu
FROM users u
WHERE u.idu != $idu
AND u.idu NOT IN
(
SELECT IF(b.idu = $idu, b.idb, b.idu)
FROM banned b
WHERE b.idu = $idu OR b.idb = $idu
)
ORDER BY RAND()
LIMIT 1 |