본문 바로가기
WEB/PHP

[PHP]MySQL_JOIN (+ambiguous error)

by 겅아링 2020. 9. 9.
반응형

name 테이블과 count 테이블을 join하여 표시하기!

name 테이블

 

count 테이블

 

 

select * from nameTBL a inner join countTBL b on a.id=b.id;

 

결과> 

 

 

 

 

특정 column만 출력하기

 

select id,name,count from nameTBL a inner join countTBL b on a.id=b.id;

결과>

ambiguous error

: id column이 nameTBL과 countTBL에도 존재하기때문에 어느 테이블의 id인지 명시해줘야한다!

 

 

 

 

select a.id,name,count from nameTBL a inner join countTBL b on a.id=b.id;

결과>

 

 

간략화한 코드

<?php
	try{
          $conn=new PDO("mysql:host=localhost;dbname=testdb","root","111111");
          $stmt=$conn->prepare("select a.id,name,count from nameTBL AS a, countTBL AS b where a.id=b.id");
          $stmt->execute();
          while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
            echo $row['id'] . " : " . $row['name'] . " : " . $row['count'];
          }
    	}catch (PDOException $e){
    		echo $e->getMessage();
    	}
?>

 

반응형