mysql - 数据库JOIN查询
ringa_lee
ringa_lee 2017-04-17 16:46:16
[MySQL讨论组]
ringa_lee
ringa_lee

ringa_lee

全部回复(2)
天蓬老师


drop table if exists article;
drop table if exists category;
drop table if exists r_ac;

create table article(
id serial not null,
title varchar(100),
expire timestamp,
primary key(id)
);

create table category(
id serial not null,
name varchar(50),
primary key(id)
);

create table r_ac(
article int not null,
category int not null,
primary key(article, category)
);



insert into article(title, expire) values ('a', '2017-05-20'),('b', null),('c', '2017-03-04'),('d', '2017-02-23'),('e', '2017-04-23'),('f', '2016-09-15'),('g', '2017-06-09');
insert into category(name) values ('c1'),('c2'),('c3'),('c4'),('c5'),('c6'),('c7');
insert into r_ac (article, category) values
(1, 1), (1, 2), (1, 5), (1, 7),
(2, 1), (2, 6),
(3, 5),
(4, 1), (4, 4),
(7, 1), (7, 7);



select category, c.name, count(1) as c from r_ac as ac
inner join (
select id, title, expire from article where expire is null or expire>now()
) as z on ac.article=z.id
left join category as c on ac.category=c.id
group by category, c.name;





高洛峰
select c.id,count(a.id) from category c LEFT JOIN r_ac r on r.category=c.id
LEFT JOIN article a on a.id=r.article and ifnull(a.expire>NOW(),1)
GROUP BY c.id 
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号