Program Tip

PHP 및 MYSQL : JOIN 작업에서 모호한 열 이름을 해결하는 방법은 무엇입니까?

programtip 2020. 10. 25. 12:50
반응형

PHP 및 MYSQL : JOIN 작업에서 모호한 열 이름을 해결하는 방법은 무엇입니까?


내 데이터베이스에 두 개의 테이블이 있습니다.

NEWS ( 'id'-뉴스 ID, 'user'-작성자의 사용자 ID)

USERS ( 'id'-사용자 ID)

SELECT * FROM news JOIN users ON news.user = user.id이제 PHP에서 결과를 얻으면 다음과 같이 만들고 싶습니다.

$row = mysql_fetch_array($result), 열 이름 가져 오기 $row['column-name']... 같은 열 이름을 가진 뉴스 ID와 사용자 ID를 얻으려면 어떻게해야합니까?

업데이트 : 빠른 답변에 감사드립니다. 별칭은 최상의 솔루션으로 보입니다.


선택중인 열에 대한 별칭을 설정할 수 있습니다.

$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'

숫자 인덱스 ( $row[0])를 사용하거나 더 나은 방법 AS으로 MySQL에서 사용할 수 있습니다 .

SELECT *, user.id AS user_id FROM ...


나는 이것을 알아 냈다. 아마도 나쁜 습관이지만이 경우에는 효과가있었습니다.

나는 테이블 접두사로 모든 ​​열 이름을 별칭으로 작성하거나 작성하고 싶지 않은 게으른 사람들 중 한 명입니다.

table_name.*select 문에서 를 사용하여 특정 테이블의 모든 열을 선택할 수 있습니다 .

중복 된 열 이름이 있으면 mysql이 처음부터 끝까지 덮어 씁니다. 중복 된 첫 번째 열 이름의 데이터는 해당 열 이름을 다시 만날 때 덮어 씁니다. 따라서 마지막에 오는 중복 열 이름이 이깁니다.

각각 중복 된 열 이름을 포함하는 3 개의 테이블을 조인하는 경우 select 문에있는 테이블의 순서에 따라 중복 된 열에 대해 가져올 데이터가 결정됩니다.

예:

SELECT table1.* , table2.* , table3.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;

위의 예에서 dupI get 의 값은 table3.

내가 dup가치가되고 싶다면 table1?

그런 다음이 작업을 수행해야합니다.

SELECT table3.* , table2.* , table1.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;

이제 table1마지막에 dup오므로의 값은 table1의 값이됩니다.

나는 dup모든 열을 작성하지 않고도 원하는 값을 얻었으며 여전히 모든 열을 사용할 수 있습니다. 예이!

의 값이 dup세 테이블 모두에서 동일해야한다는 것을 알고 있지만 table3일치하는 값이 없으면 dup어떻게됩니까? 그러면 dup첫 번째 예에서 공백이되며 이는 당황 스러울 것입니다.


또 다른 팁 : 더 깨끗한 PHP 코드를 원한다면 데이터베이스에 VIEW를 생성 할 수 있습니다.

예를 들면 :

CREATE VIEW view_news AS
SELECT
  news.id news_id,
  user.id user_id,
  user.name user_name,
  [ OTHER FIELDS ]
FROM news, users
WHERE news.user_id = user.id;

PHP에서 :

$sql = "SELECT * FROM view_news";

다음과 같이 할 수 있습니다.

SELECT news.id as news_id, user.id as user_id ....

그런 다음 $row['news_id']뉴스 ID가되고 $row['user_id']사용자 ID가됩니다.


@ 제이슨. php가 mysql이 아니라 범인이라는 점을 제외하고는 정확합니다. JOINMysql Workbench에 넣으면 정확히 동일한 이름 (각 테이블에 하나씩)을 가진 3 개의 열을 얻지 만 동일한 데이터는 포함하지 않습니다 (일부는 null해당 테이블에 일치하는 항목이없는 경우 JOIN).

PHP MYSQL_NUM에서 in mysql_fetch_array()사용 하면 모든 열을 얻을 수 있습니다. 사용할 때 문제는 mysql_fetch_array()함께 MYSQL_ASSOC. 그런 다음 해당 함수 내에서 php는 다음과 같이 반환 값을 작성합니다.

$row['dup'] = [value from table1]

그리고 나중에 ...

$row['dup'] = [value from table2]

...

$row['dup'] = [value from table3]

따라서 table3의 값만 얻을 수 있습니다. 문제는 mysql의 결과 집합이 동일한 이름의 열을 포함 할 수 있지만 PHP의 연관 배열은 배열의 중복 키를 허용하지 않는다는 것입니다. 데이터가 연관 배열에 저장되면 PHP에서 일부 정보가 자동으로 손실됩니다.


I had this same issue with dynamic tables. (Tables that are assumed to have an id to be able to join but without any assumption for the rest of the fields.) In this case you don't know the aliases before hand.

In such cases you can first get the table column names for all dynamic tables:

$tblFields = array_keys($zendDbInstance->describeTable($tableName));

Where $zendDbInstance is an instance of Zend_Db or you can use one of the functions here to not rely on Zend php pdo: get the columns name of a table

Then for all dynamic tables you can get the aliases and use $tableName.* for the ones you don't need aliases:

$aliases = "";
foreach($tblKeys as $field)
    $aliases .= $tableName . '.' . $field . ' AS ' . $tableName . '_' . $field . ',' ;
$aliases = trim(',', $aliases);

You can wrap this whole process up into one generic function and just have cleaner code or get more lazy if you wish :)


If you don't feel like aliassing you can also just prefix the tablenames.

This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need Furthermore, only explicitly name the fields you want to have.

SELECT
    news.id, news.title, news.author, news.posted, 
    users.id, users.name, users.registered 
FROM 
    news 
LEFT JOIN 
    users 
ON 
    news.user = user.id

There are two approaches:

1. Using aliases; in this method you give new unique names (ALIAS) to the various columns and then use them in the PHP retrieval.

eg.

SQL $sql = SELECT student_id FEES_LINK, student_class CLASS_LINK from students_fee_tbl LEFT JOIN student_class_tbl ON students_fee_tbl.student_id=student_class_tbl.student_id

PHP $query = mysql_fetch_assoc($sql);//if using the old approach

$query = PDO->fetchAll(); //not exact syntax but this is the current approach

foreach($query as $q){
echo $q['FEES_LINK'];
}

2.

Using place position or resultset column index; in this, the array positions are used to reference the duplicated column names. Since they appear at different positions, the index numbers that will be used is always unique. However, the index positioning numbers begins at 0.

eg.

$sql = SELECT student_id, student_class from students_fee_tbl LEFT JOIN student_class_tbl ON students_fee_tbl.student_id=student_class_tbl.student_id

PHP

$query = mysql_fetch_assoc($sql);//if using the old approach

$query = PDO->fetchAll();//not exact syntax but this is the current approach

foreach($query as $q){

    echo $q[0];

}

the two works.

Hope it helps. :)

참고URL : https://stackoverflow.com/questions/431391/php-mysql-how-to-resolve-ambiguous-column-names-in-join-operation

반응형