본문 바로가기
MySql

MySQL mySQL에서 두 테이블에서 선택하고 열을 병합 할 수 있습니까?

by 베이스 공부 2020. 11. 22.
반응형

비슷한 열을 가진 mysql에 두 개의 테이블이 있다면 ...

TABLEA
  id
  name
  somefield1

TABLEB 
  id
  name
  somefield1
  somefield2

두 테이블에서 동시에 SELECT 할 수 있고 동일한 열에 대해 결과 집합을 병합 할 수 있도록 SELECT 문을 어떻게 구성합니까?

예를 들어, 저는 다음과 같은 일을하고 싶습니다.

SELECT name, somefield1 FROM TABLEA, TABLEB WHERE name="mooseburgers";

... 이름이 있고 두 테이블의 somefield1 열이 결과 집합에 병합됩니다.

도와 주셔서 감사합니다!

질문이 명확하지 않아 추가 된 샘플 출력 :

나는 table1의 행과 table2의 행을 결과 집합에 추가하고 싶습니다. 예를 들어 테이블에

TABLEA
id(1) name(zoot) somefield(suit)

TABLEB
id(1) name(zoot) somefield(flute)

The resultet would look like:

name     |     somefield1
zoot           suit
zoot           flute

 

해결 방법

 

(id, name)을 조인 기준으로 사용하여 두 테이블의 열을 다음과 함께 결합 할 수 있습니다.

select
    a.id                               as id,
    a.name                             as name,
    a.somefield1 || ' ' || b.somefied1 as somefield1
from tablea a, tableb b
where a.id   = b.id
  and a.name = b.name
  and b.name = 'mooseburgers';

(id) 만 조인하고 name 및 somefield1 열을 결합하려는 경우 :

select
    a.id                               as id,
    a.name || ' ' || b.name            as name,
    a.somefield1 || ' ' || b.somefied1 as somefield1
from tablea a, tableb b
where a.id   = b.id
  and b.name = 'mooseburgers';

나는 이것이 일을하는 다소 특이한 방법임을 인정해야합니다. 그러나 나는 당신이 당신의 이유가 있다고 가정합니다 :-)

내가 귀하의 질문을 오해하고 두 테이블의 더 일반적인 결합을 원하면 다음과 같이 사용하십시오.

select id, name, somefield1, '' as somefield2 from tablea where name = 'mooseburgers'
union all
select id, name, somefield1, somefield2 from tableb where name = 'mooseburgers'

이것은 행을 결합 하지 않고 대신 두 쿼리의 행을 추가합니다. 중복 행을 제거하려는 경우 자체적으로 union 을 사용하지만 중복이없는 것이 확실하거나 제거하지 않으려는 경우 union all 이 자주 사용됩니다. 더 효율적입니다.

편집 내용에 따라 실제 쿼리는 다음과 같습니다.

select name, somefield1 from tablea where name = 'zoot'
union all
select name, somefield1 from tableb where name = 'zoot'

(또는 a.name == b.name == 'zoot' a.somefield1 == b.somefield1에서 중복을 원하지 않는 경우 union ) ).

 

참조 페이지 https://stackoverflow.com/questions/2913338

 

 

반응형

댓글