[英]Could not figure out a SQL Query to relate both tables
Ok, I have two tables. 好的,我有两个桌子。
Table 'topic' 表“主题”
tid | posts
------------
1 4
3 2
Table 'posts' 表“帖子”
topic_id | post
-----------------
1 xxxx
3 aaaa
1 dddd
1 ddsdss
3 rreer
1 gsdsd
My abstract query is like this: 我的抽象查询是这样的:
select counter(*) as c
from posts as p, topic as t
where p.tid = t.topicid
and c != t.posts
This should return counter of all 'posts' table rows which matches with 'topic' table tid and also does not matche with Table 'topic' posts count. 这应返回所有与“主题”表tid匹配且也与“主题”表的计数不匹配的“表”表行的计数器。
Also I need to update the colum "posts" of topic with the counter(*) value if found different. 另外,如果发现不同,我还需要使用counter(*)值更新主题的“职位”。
update topic set posts = (SELECT COUNT(*) from posts WHERE posts.topicid = topic.tid and topic.posts <> (SELECT COUNT(*) from posts WHERE posts.topicid = topic.tid))
I tried many ways to get this working, but could not figure out. 我尝试了许多方法来使此工作正常进行,但无法弄清楚。 Would really appreciate if anyone can explain a query for this case ? 如果有人可以解释这种情况的查询,我们将不胜感激?
Actually what I am trying do is this. 其实我正在尝试做的就是这个。 I want to update posts counter of topic for all the matching topic ids between table if posts count of 'posts' table does not match 'topic' table posts counter. 如果“帖子”表的帖子计数与“主题”表的帖子计数器不匹配,我想为表之间所有匹配的主题ID更新主题的帖子计数器。 You get me ? 你懂我吗? I tried to play with your query, but it does other way of giving me 'topic' table rows instead which is not I want. 我试图处理您的查询,但是它以其他方式给我“主题”表行,而这不是我想要的。
UPDATE topics SET posts = (
SELECT COUNT(*)
FROM posts
WHERE topicid = (
SELECT tid
FROM topics
WHERE topics.tid = topicid
)
GROUP BY topicid HAVING COUNT(*) <> (
SELECT posts
FROM topics WHERE topics.tid = topicid
)
) **WHERE tid = (
SELECT topicid
FROM posts
WHERE topicid = (
SELECT tid
FROM topics
WHERE topics.tid = topicid
) GROUP BY topicid HAVING COUNT(*) <> (
SELECT posts FROM topics WHERE topics.tid = topicid
)
)**
The following will give you the topic and count 以下将给您主题和计数
If you want to find the topics that are "wrong" then join this to the the count table 如果要查找“错误”的主题,则将其加入计数表
SELECT *
FROM topic
LEFT JOIN (
SELECT topic_id, count(*) as t_count
FROM posts
GROUP BY topic_id
) sub on topic.tid = sub.topic_id
Then to see the ones that are different you can add a where 然后,要查看不同的内容,可以在其中添加
WHERE topic.posts <> sub.t_count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.