2013-06-06 3 views
3

mysql에 두 개의 테이블이 있습니다.왼쪽 외부 조인과 평균이있는 mysql 쿼리

name   service   number 
    carlos   telephone   6 
    juan    watter   12 
    maria    gas   23 
    jhon    hostal   17 
    marcos   sleeping  21 
    carlos   othercarlos  12 
    other    other   13 

그리고 난 다른 테이블 별칭

name    service   alias    price 
    carlos   telephone  telephone-carlos  700 
    carlos   sleeping   sleeping-carlos  300 
    juan    watter   watter-juan   900 
    maria    gas   gas-maria   650 
    jhon    hostal   hostal-jhon   700 

을 가지고 있고 이름, 별명, 수와 왕자와 뷰를 필요로 : 첫 번째 테이블 이름은 다음과 같은 날짜가 있습니다. 하지만 이름이 왼쪽 행 외부 조인으로 모든 행이 필요합니다. 하지만 문제는 내가 쿼리를 할 때 othercarlos가 필요하다는 것입니다. 가격은 카를로스 서비스의 평균이 될 것이고 이름이 다른 경우 나는 모든 서비스의 평균을 나타낼 필요가 있습니다. 그러나 표시 널 (null)

http://sqlfiddle.com/#!2/c1d4f/1

나는이 작업을 수행하는 더 나은 방법이 있다고 확신 해요,하지만 난 적어도 당신에게 한 가지 방법을 제공 할 수

+1

훌륭한 일! 나는 아직도 그 질문을 이해할 수 없다. 출력을 포함시킬 수 있습니까? –

+0

원하는 결과를 게시 할 수 있습니까? – Lamak

답변

3

확인이 테이블 내 쿼리를 만들 :

SELECT t1.name, 
     t1.service, 
     t2.alias, 
     t1.number, 
     COALESCE(t2.price,t3.price,t4.price) AS price 
FROM name t1 
LEFT JOIN alias t2 
    ON t1.name= t2.name 
    AND t1.service = t2.service 
LEFT JOIN (SELECT name, AVG(price) AS price 
      FROM alias 
      GROUP BY name) t3 
    ON t1.name = t3.name 
LEFT JOIN (SELECT AVG(price) AS price 
      FROM alias) t4 
    ON t1.name = 'other' 

Here is a fiddle이 있습니다.

결과 : 바이올린 포함

╔════════╦═════════════╦══════════════════╦════════╦═══════╗ 
║ NAME ║ SERVICE ║  ALIAS  ║ NUMBER ║ PRICE ║ 
╠════════╬═════════════╬══════════════════╬════════╬═══════╣ 
║ carlos ║ telephone ║ telephone-carlos ║  6 ║ 700 ║ 
║ juan ║ watter  ║ watter-juan  ║  12 ║ 900 ║ 
║ maria ║ gas   ║ gas-maria  ║  15 ║ 250 ║ 
║ jhon ║ hostal  ║ hostal-jhon  ║  21 ║ 640 ║ 
║ carlos ║ sleeping ║ sleeping-carlos ║  24 ║ 300 ║ 
║ carlos ║ othercarlos ║ (null)   ║  11 ║ 500 ║ 
║ other ║ (null)  ║ (null)   ║  2 ║ 558 ║ 
╚════════╩═════════════╩══════════════════╩════════╩═══════╝ 
관련 문제