按条件联接两个表

时间:2018-10-02 10:50:25

标签: php mysql join group-by

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

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_month     parent_category     
1         2018-10           5   
2         2018-10           5   
3         2018-11           5   
4         2018-11           5   
5         2018-10           6   

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

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

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

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

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

2 个答案:

答案 0 :(得分:2)

使用非重复

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_month BETWEEN '{$from}' AND '{$to}'
order by B.paying_month

答案 1 :(得分:1)

根据您的表格,“ Thrikandiyur Quarters”仅与“ 2018-10”相关。因此,在您的输出中包含以下行:“ Thrikandiyur Quarters 2018-11”,您应该在表b中有一个引用,如下所示:

id  ||   paying_month  ||   parent_category  
6   ||    2018-11      ||    6 

您所使用的条件只是两个日期之间。要获得不重复的输出,应在语句中放置“ DISTINCT”。像这样:

$query=$this->db->query("SELECT DISTINCT * from tableA A left join tableB B  on 
A.category_id = B.parent_category and B.paying_month BETWEEN '{$from}' AND 
'{$to}' ");

另一种解决方案是使用“ GROUP BY”:

$query=$this->db->query("SELECT * from tableA A left join tableB B  on 
A.category_id = B.parent_category and B.paying_month BETWEEN '{$from}' AND 
'{$to}' GROUP BY B.parent_category");