mysqli左连接重复行

时间:2017-03-02 01:32:42

标签: php mysql

表com

id | com       | id_status  
1    testing 1   1  
2    testing 2   1  
3    testing 3   2  
4    testing 4   2  

表格更新

id_status | update  
1           update 1  
2           update 2  
3           update 3  


SELECT `update`.`update`, `com`.`com` as comen
FROM `update` 
    LEFT JOIN `com` ON `update`.`id_status`=`com`.`id_status`  

结果:

update 1  
testing 1  
update 1  
testing 2  
update 2  
testing 3  
update 2  
testing 4  

更新表结果重复

我已完成update id_status小组的使用,结果是:

update 1  
testing 1  
testing 2  
update 3  

表格com仅重新开始1行

修改 -
我从这个MySQL LEFT JOIN display duplicate rows

获得了语法
$first = true;  
while($row = $query->fetch_object()){  
if($first){  
    echo $row->update;  
    $first = false;  
    echo "<br>";  
}  
echo $row->comen;  
echo "<br>";  
}  

update 1  
testing 1  
testing 2  
testing 3  
testing 4  

它只获取1个表格行

我希望结果如下:

update 1  
testing 1  
testing 2  
update 2  
testing 3  
testing 4  
update 3  
...  

-

正确的语法如何工作或者查询?

3 个答案:

答案 0 :(得分:0)

使用INNER JOIN代替左连接

SELECT `update`.`update`, `com`.`com` as comen
FROM `update` INNER JOIN `com` ON `update`.`id_status`=`com`.`id_status`; 

或者可以使用DISTINCT关键字来避免重复结果

SELECT DISTINCT `com`.`id_status`, `update`.`update`, `com`.`com` as comen
FROM `update` LEFT JOIN `com` ON `update`.`id_status`=`com`.`id_status`;

答案 1 :(得分:0)

根据您的查询,结果应该没问题。让我们看一下表 com 包含两个值 id_status = 1

现在,如果您使用更新表离开 com 表,则查询将给出2行对应的id_status = 1,因为 com 表包含两行id_status是1。

如果您只想获得任何一行记入id_status,那么您必须使用 group by update.id-status group by com.id-status < / p>

 SELECT `up`.`up`, `com`.`com` as comen FROM `up` LEFT JOIN `com` ON `up`.`id_status`=`com`.`id_status` group by up.id_status 

我用完了而不是更新,因为update是一个关键字。 表:

com table Up table

结果:

enter image description here

答案 2 :(得分:0)

试试这个,我想这会解决: -

SELECT `update`.`update`, group_concat(`com`.`com`) as comen
FROM `update` 
    LEFT JOIN `com` ON `update`.`id_status`=`com`.`id_status` 
Group by `update`.`update`

并使用你的php: -

while($row = $query->fetch_object()){  
    echo $row->update;  
    $comen = explode(",", $row->comen);
    foreach($comen as $values){
     echo "<br>";  
     echo $values;
    }
    echo "<br>";  
}