mysql - 如何比较父表和子表

标签 mysql

我有三个表:crawl_post、crawl_image 和crawl_video。

创建表crawl_post ( Id int NOT NULL AUTO_INCRMENT, 图像计数 int, 视频计数 int 主键(ID) );

创建表crawl_image ( Id int NOT NULL AUTO_INCRMENT, 状态 bool 值 帖子 ID 整数 主键(ID) );

创建表crawl_video ( Id int NOT NULL AUTO_INCRMENT, 状态 bool 值 帖子 ID 整数 主键(ID) );

状态 = true - 已下载,false - 未下载

通过查询,我想选择所有下载了图像和视频的帖子?这意味着,count(下载的图像) = post.Imagecount 和 count(下载的视频) = post.VideoCount。

感谢您的帮助。

最佳答案

使用join子句很容易实现这一点,如下所示:

select
    c1.*
from
    crawl_post c1
join
    crawl_image c2 on c1.id = c2.postid and c2.status = 1
join
    crawl_video c3 on c1.id = c3.postid and c3.status = 1

上面的 SQL 将返回所有下载了图像和视频的帖子的结果。

好吧,我试图理解你想要什么,你只是想获得完成所有图像和视频下载操作的帖子,对吗?我重新编辑如下:

select cp.* from (
select
    c1.id,
    count(c2.postid) as imageFinishedCount
    count(c3.postid) as videoFinishedCount
from
    crawl_post c1
left join
    crawl_image c2 on c1.id = c2.postid and c2.status = 1
left join
    crawl_video c3 on c1.id = c3.postid and c3.status = 1
group by
    c1.id
) tmp 
join 
    crawl_post cp on tmp.id = cp.id 
where 
    tmp.imageFinishedCount = cp.imageCount and tmp.videoFinishedCount = cp.videoCount

关于mysql - 如何比较父表和子表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56230414/

相关文章:

mysql - 如何使用 Sequelize 在 Node.js 中延迟触发器创建

MySQL:如果行不存在则返回 0

java - 我有 hibernate 错误

mysql - WHERE CURDATE() < end_date AND WHERE title LIKE '%test%'

php - PDO 使用 WHERE id=6ff 等语句选择 id=6 的行

mysql - 另一个数据透视表查询

php - 使用 PHP 登录 MySQL - 多久一次?

MySQL = 按月份对销售计数进行分组,然后将月份显示为名称(一月、二月...十二月)而不是数值(1,2,3-12)

mysql - SQL 填充常量以防连接两个表时不匹配

php - 如果字符串已存在,则在字符串后添加数字