mysql - 數(shù)據(jù)庫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
相關(guān)文章:
1. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?2. dockerfile - [docker build image失敗- npm install]3. mysql如何配置遠(yuǎn)程php外網(wǎng)鏈接數(shù)據(jù)庫4. javascript - vue使用videojs+videojs-contrib-hls報(bào)錯5. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””6. javascript - 怎么下載vue csp版本的2.0或者以上?7. io - java 文件操作,如何向指定的位置插入內(nèi)容 (不是替換內(nèi)容) ?8. golang - 用IDE看docker源碼時的小問題9. javascript - 求救!網(wǎng)頁播放視頻只有聲音沒有畫面,網(wǎng)頁上傳視頻文件時怎么知道視頻的編碼為H264還是MPEG4??10. Python 爬蟲 遇到的問題(手淘問大家)
