mysql - 數(shù)據(jù)庫(kù)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. php - 有關(guān)sql語句反向LIKE的處理2. fetch_field_direct()報(bào)錯(cuò)3. 在視圖里面寫php原生標(biāo)簽不是要迫不得已的情況才寫嗎4. 獲取上次登錄ip的原理是啥?5. 求救一下,用新版的phpstudy,數(shù)據(jù)庫(kù)過段時(shí)間會(huì)消失是什么情況?6. phpstudy v8打開數(shù)據(jù)庫(kù)就出錯(cuò),而phpstudy 2018不會(huì)7. 為什么說非對(duì)象調(diào)用成員函數(shù)fetch()8. 為什么點(diǎn)擊登陸沒反應(yīng)9. 請(qǐng)問下tp6框架的緩存在哪里設(shè)置,或者說關(guān)閉?10. mysql報(bào)錯(cuò) unknown column ’a.plat’ in ON clause
