从表中获取行,忽略subselect的结果

时间:2015-02-04 20:56:39

标签: mysql sql

考虑这样一个表:

CREATE TABLE IF NOT EXISTS `books` (
  `id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `original_id` int(8) unsigned DEFAULT NULL,
  `user_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `original_id` (`original_id`)
);


INSERT INTO `books` (`id`, `title`, `original_id`, `user_id`) VALUES
(14, 'A Title', NULL, 0),
(26, 'Another title', NULL, 0),
(27, 'A Third Title', NULL, 0),
(29, 'A Title', 14, 4),
(30, 'A Forth Title', NULL, 0),
(31, 'A Fifth Title', NULL, 0),
(32, 'A Third Title', 27, 4),
(33, 'A Sixth Title', NULL, 0),
(34, 'A Forth Title', 30, 6);

SQLFiddle:http://sqlfiddle.com/#!2/3857e/1

user_id = 0是公共记录

user_id> 0是源自公共记录的私人记录,其中original_id是指原始记录

我需要获得满足文本搜索的行,不包括第三方记录(到目前为止没有问题),以及我的副本所在的原始行。

是否可以仅使用select + subselect来获取它?

3 个答案:

答案 0 :(得分:1)

对以下内容进行一些修改会有所帮助;

select * from books a
where a.original_id is null
and not exists (select 'a' from books b
where a.id = b.original_id)

答案 1 :(得分:1)

“我”是4

SELECT b1.* FROM books b1
LEFT JOIN books b2
  ON b2.original_id = b1.id AND b2.user_id = 4
WHERE (b1.user_id = 0 AND b2.id IS NULL)
  OR b1.user_id = 4

(b1.user_id = 0 AND b2.id IS NULL)获取我未复制的公开内容。

b1.user_id = 4得到我的。

答案 2 :(得分:0)

我仍然不清楚你的需求,但这样的事情对你有用吗?

SELECT * 
FROM books AS b 
WHERE b.title LIKE '%mySearchStr%'
  AND b.user_id IN (0, myUserID)
  AND b.id NOT IN 
    (SELECT DISTINCT b2.original_id 
     FROM books AS b2 
     WHERE b2.user_id NOT IN (0, myUserID)
    )
;