我有两张桌子:
标题
- ID
- 标题
输入
- ID
- 输入
- 的title_id
- USER_ID
- 时间(时间戳)
我需要检查在我最后一次输入该标题后是否提交了新条目。在每个标题上查找过滤更新(与我的user_id不同)的查询,并列出包含显示新条目的数字的结果。
标题
id | title
1 | Cars
2 | Computers
输入
id | entry | title_id | user_id | time
1 | bmw | 1 | 1 | 1418595811
2 | mercedes | 2 | 2 | 1418595812
3 | ibm | 2 | 2 | 1418595813
4 | hp | 2 | 3 | 1418595814
5 | dell | 2 | 1 | 1418595815
6 | acer | 2 | 3 | 1418595816
7 | asus | 2 | 4 | 1418595817
8 | toshiba | 2 | 4 | 1418595818
9 | ferrari | 1 | 3 | 1418595819
10 | toyota | 1 | 4 | 1418595820
11 | honda | 1 | 2 | 1418595821
预期结果:
如果user_id = 1 - >
Cars (3)
Computers (3)
如果user_id = 2 - >
Cars (0)
Computers (5)
如果user_id = 3 - >
Cars (2)
Computers (2)
如上所示,[user_id = 1]提交汽车(宝马)。之后,其他用户提交了该标题的条目。用户上次提交后,我需要查询每个标题的新提交。 (使用时间字段) 唯一需要的是,如果有新的提交。如果是这样,有多少?
我需要这样的东西:
select count(entry)
from entry where time>last_entry_time[user_id]
left join titles
where title.id=entry.title_id
答案 0 :(得分:1)
这适用于所有用户:
SELECT e1.user_id, t.title, COUNT(e2.id) AS count
FROM titles AS t
LEFT JOIN (SELECT user_id, title_id, MAX(time) AS last_entry
FROM entry
GROUP BY user_id, title_id) AS e1
ON t.id = e1.title_id
LEFT JOIN entry AS e2 ON e2.title_id = e1.title_id AND e2.user_id != e1.user_id AND e2.time > e1.last_entry
GROUP BY e1.user_id, t.id
ORDER BY e1.user_id, t.title
为特定用户执行此操作:
SET @user_id = 1;
SELECT t.title, COUNT(e2.id) AS count
FROM titles AS t
LEFT JOIN (SELECT user_id, title_id, MAX(time) AS last_entry
FROM entry
WHERE user_id = @user_id
GROUP BY title_id) AS e1
ON t.id = e1.title_id
LEFT JOIN entry AS e2 ON e2.title_id = e1.title_id AND e2.user_id != @user_id AND e2.time > e1.last_entry
GROUP BY t.id
ORDER BY t.title
答案 1 :(得分:0)
我不确定我是否正确地关注了您的问题。试试这个
select e.id, e.tittle_id, e.user_id from entry e
where e.id not in(
select e.id from entry e, titles t where t.id = e.id
)