取决于表中列的值从两个不同的表中获取数据

时间:2014-02-17 08:10:19

标签: mysql sql sql-server

我有三个表USERSCOMPANIESORGANIZATIONS

USERS包含:USER_ID,USER_OWNER_ID,OWNER_TYPE,USER_NAME

COMPANIES包含:COMPANY_ID,COM​​PANY_NAME

ORGANIZATIONS包含:ORGANIZATION_ID,ORGANIZATION_NAME

我的要求是,如果COMPANIES.COMPANY_NAME为20,则必须获取USERS.OWNER_TYPE,如果ORGANIZATIONS.ORGANIZATION_NAME为30,则必须获得USERS.OWNER_TYPE

所以,我使用了以下查询

SELECT US.USER_NAME,
       US.USER_OWNER_ID,
       IF ( 
           US.OWNER_TYPE=20, ORG.ORGANIZATION_NAME, CO.COMPANY_NAME
           ) AS NAME 
  FROM USERS US, 
       COMPANIES CO, 
       ORGANIZATIONS ORG 
 WHERE (US.OWNER_TYPE=20 AND US.USER_OWNER_ID=ORG.ORGANIZATION_ID) 
       OR 
       (US.OWNER_TYPE=30 AND US.USER_OWNER_ID=CO.COMPANY_ID)

问题在于我从OWNERS表中获得了OWNER_TYPE = 30的重复记录。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你可以尝试

SELECT us.user_name, 
       us.user_owner_id,
       COALESCE(co.company_name, org.organization_name) AS name
 FROM users us LEFT JOIN companies co
   ON us.user_owner_id = co.company_id
  AND us.owner_type = 30 LEFT JOIN organizations org 
   ON us.user_owner_id = org.organization_id
  AND us.owner_type = 20

示例输出:

| USER_NAME | USER_OWNER_ID |          NAME |
|-----------|---------------|---------------|
|     User1 |             1 | Organization1 |
|     User2 |             1 |      Company1 |

这是 SQLFiddle 演示

答案 1 :(得分:-1)

我认为这会很快,

SELECT us.*  
  FROM users us 
       INNER JOIN COMPANIES co 
                  ON US.OWNER_TYPE=30 
                  AND US.USER_OWNER_ID=CO.COMPANY_ID
UNION ALL
SELECT us.*  
  FROM users us 
       INNER JOIN ORGANIZATIONS org (
       US.OWNER_TYPE=20 
       AND US.USER_OWNER_ID=ORG.ORGANIZATION_ID
       )