mysql - 数据库JOIN查询
问题描述
问题解答
回答1: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 acinner join (select id, title, expire from article where expire is null or expire>now()) as z on ac.article=z.idleft join category as c on ac.category=c.idgroup by category, c.name;回答2:
select c.id,count(a.id) from category c LEFT JOIN r_ac r on r.category=c.idLEFT JOIN article a on a.id=r.article and ifnull(a.expire>NOW(),1)GROUP BY c.id
相关文章:
1. 编辑管理员信息时,为什么没有修改过的内容会为空?2. thinkphp中Controller里面使用Request::File(’image’);3. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?4. node.js - vue项目在c盘外,npm run dev 出错,求指点。5. mysql - 看这条sql有可能被注入吗6. javascript - js中数组的undefined为什么不会被遍历7. java 如何列出jar包中jar包里的所有文件和目录?8. html - angularJS中switch切换开关按钮不能操作9. javascript - 如何将一个长为365的数组对象按月份切割成12组?10. css3不包括

网公网安备