通过按条件分组使结果唯一

时间:2018-10-15 07:04:33

标签: php mysql join group-by distinct

在这里我想加入两个表并想产生类似的输出

Akbar Travels building      2018-10
Thrikandiyur Quarters       2018-10


Akbar Travels building     2018-11
Thrikandiyur Quarters      2018-11

这里我有两个表名table A,table Btable A结构如下

 category_id           category_name    
    5               Akbar Travels building          
    6               Thrikandiyur Quarters

table B结构如下

id   paying_date   paying_month     parent_category     
1    2018-10-01      2018-10            5   
2    2018-10-01      2018-10            5   
3    2018-10-01      2018-11            5   
4    2018-11-01      2018-11            5   
5    2018-10-01      2018-10            6
6    2018-10-10      2018-12            5

为了获得输出,我这样写了我的代码

public function get_date_wise_pdf_report($from, $to)
{
       $query=$this->db->query("SELECT distinct A.category_name,B.paying_month from tableA A left join tableB B  on A.category_id = B.parent_category and B.paying_date BETWEEN '{$from}' AND '{$to}' order by B.paying_month");
       return $query->result();
 }

但是当我使用它时,会变得像这样

Akbar Travels building     2018-10
Thrikandiyur Quarters      2018-10
Akbar Travels building     2018-10
Thrikandiyur Quarters      2018-10

在这里我无法按组给出陈述,如果我只给出两行的话,请帮我解决

1 个答案:

答案 0 :(得分:1)

尝试使用子查询

demo

 select distinct catname,paymon
from
(SELECT A.catname,DATE_FORMAT(B.paydate, "%Y-%m") as paymon from  A 
left join  B  on A.catid = B.parentcatid and B.paydate BETWEEN '2018-10-01' AND '2018-12-31'
)X order by paymon