我有两张这样的表:
logbook:
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date_added | timestamp | NO | | CURRENT_TIMESTAMP | |
| username | varchar(16) | NO | | NULL | |
| entry | longtext | NO | MUL | NULL | |
+------------+-------------+------+-----+-------------------+----------------+
和
read_logbook:
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| logbook_id | int(11) | NO | | NULL | |
| username | varchar(16) | NO | | NULL | |
+------------+-------------+------+-----+---------+----------------+
我想做的是从logbook
选择一切,但仅当logbook.id
和logbook.username
不会出现在read_logbook.logbook_id
和{{read_logbook.username
时1}},分别。
我已经尝试了一些左联合权限查询以及一些not in
查询,并且不断获得比预期更多的结果,或者根本没有结果。
有什么想法吗?
编辑 - 我为特定的用户名运行此操作...所以基本上,如果我的用户名是jmd9qs
,我希望{{1}的所有结果1}} logbook
!= read_logbook.id
和logbook.id
!= read_logbook.username
我希望这很清楚......
编辑 - 测试数据
日志:
jmd9qs
已经标记为"的日志条目"正如:
mysql> select id, date_added, username from logbook order by id desc limit 10;
+----+---------------------+-----------+
| id | date_added | username |
+----+---------------------+-----------+
| 94 | 2013-09-03 14:54:25 | tluce |
| 93 | 2013-09-03 13:12:02 | tluce |
| 92 | 2013-09-03 11:42:14 | tluce |
| 91 | 2013-09-03 08:28:20 | jmd9qs |
| 90 | 2013-09-03 07:13:36 | jmd9qs |
| 89 | 2013-09-03 07:05:19 | jmd9qs |
| 88 | 2013-09-03 06:57:47 | jsawtelle |
| 87 | 2013-09-03 06:15:42 | jsawtelle |
| 86 | 2013-09-03 05:21:14 | jsawtelle |
| 85 | 2013-09-03 03:52:25 | jsawtelle |
+----+---------------------+-----------+
因此,当我运行mysql> select logbook_id, username from read_logbook group by logbook_id desc limit 10;
+------------+----------+
| logbook_id | username |
+------------+----------+
| 94 | jmd9qs |
| 93 | jmd9qs |
| 92 | jmd9qs |
| 91 | jmd9qs |
| 90 | jmd9qs |
| 89 | jmd9qs |
| 88 | jmd9qs |
| 87 | jmd9qs |
| 86 | jmd9qs |
| 85 | jmd9qs |
+------------+----------+
10 rows in set (0.00 sec)
的查询时,不会出现任何问题,因为在jmd9qs
中,他的用户名和日志ID会显示出来。
澄清 -
因此,在日志中,用户名只是撰写read_logbook
的人。在logbook.entry
中,用户名是读取该条目的人。因此,如果我以read_logbook
身份登录,并且我尝试查看日志,因为我已经阅读了所有内容,jmd9qs
应该出现。但对于HASN&T; T读取该特定条目的其他用户,该条目将显示出来。
答案 0 :(得分:1)
如果我了解您的需求,您应该尝试
SELECT t1.* FROM logbook t1
LEFT JOIN read_logbook t2
ON t1.id = t2.id AND t1.username = t2.username
WHERE t2.id IS NULL AND t2.username IS NULL
答案 1 :(得分:1)
SELECT *
FROM logbook
WHERE logbook.username NOT IN
(SELECT read_logbook.username
FROM read_logbook
WHERE read_logbook.username='jmd9qs')
AND logbook.id NOT IN
(SELECT read_logbook.logbook_id
FROM read_logbook);