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. 哭遼 求大佬解答 控制器的join方法怎么轉模型方法3. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?4. mysql - 數據庫表中,兩個表互為外鍵參考如何解決5. mysql儲存json錯誤6. mysql - 怎么生成這個sql表?7. mysql - 表名稱前綴到底有啥用?8. sql語句 - 如何在mysql中批量添加用戶?9. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?10. 怎么php怎么通過數組顯示sql查詢結果呢,查詢結果有多條,如圖。
