mysql - 數(shù)據(jù)庫(kù)JOIN查詢
問(wèn)題描述
問(wèn)題解答
回答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
相關(guān)文章:
1. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境2. java - Hibernate查詢的數(shù)據(jù)是存放在session中嗎?3. angular.js - angularjs的自定義過(guò)濾器如何給文字加顏色?4. c++ - win764位環(huán)境下,我用GCC為什么指針占8個(gè)字節(jié),而long是4個(gè)字節(jié)?5. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?6. angular.js - angularjs 使用鼠標(biāo)懸停時(shí),標(biāo)簽一直閃7. 一個(gè)走錯(cuò)路的23歲傻小子的提問(wèn)8. html5 - HTML代碼中的文字亂碼是怎么回事?9. python 計(jì)算兩個(gè)時(shí)間相差的分鐘數(shù),超過(guò)一天時(shí)計(jì)算不對(duì)10. python - django 里自定義的 login 方法,如何使用 login_required()
