简体   繁体   English

SELECT * FROM TABLE, TABLE 取决于另一个查询 - SQL

[英]SELECT * FROM TABLE, TABLE depending on another query - SQL

Here's what I'm trying to achieve : Select a person's or firm's name depending on the contact type.这就是我想要实现的目标:根据联系人类型选择一个人或公司的名称。

Tables :表:

CONTACTS :               PEOPLE              FIRMS
- id                     - contact_id        - contact_id    
- type (person/firm)     - name              - name

I would like this kind of magic :我想要这种魔法:

SELECT type 
FROM contacts 
WHERE contacts.id = 42;

SELECT model.name 
FROM contacts LEFT JOIN model ON model.contact_id = contacts.id 
WHERE contacts_id = 42 
AND model = CASE (WHEN type = "person" THEN "people" 
                  WHEN type = "firm" THEN "Firms" END); (Not sure this one works)

All in one query.一键查询。 Thanks !谢谢 !

You could do like below, join two tables and then decide which column to use according to contacts.type .你可以像下面那样,连接两个表,然后根据contacts.type决定使用哪一列。

SELECT 
  (CASE WHEN t1.type = 'person' THEN t2.name WHEN t1.type = 'firm' THEN t3.name) AS contact_name
FROM contacts t1
LEFT JOIN people t2 ON t1.id = t2.contact_id
LEFT JOIN firms t3 ON t1.id = t3.contact_id

You can use dynamic sql like this:您可以像这样使用动态 sql:

declare 
    @table_name nvarchar(20),
    @query nvarchar(max)

SELECT 
    @table_name = 
                    case type 
                        when 'person' then 'people'
                        when 'firm' then 'firms'
                    end
FROM contacts  
WHERE contacts.id = 42;


set @query = N'SELECT ' + @table_name + '.name ' +
                'FROM contacts LEFT JOIN model ON ' + @table_name + '.contact_id = contacts.id 
                WHERE contacts_id = 42 '

exec sp_executesql @query

Simply left join both tables;简单地左连接两个表; one of them will match id and type.其中之一将匹配 id 和类型。 Use COALESCE then to display the one name found.然后使用 COALESCE 显示找到的名称。

select coalesce(p.name, f.name) as name
from contacts c
left join people p on p.contacts_id = c.id and c.type = 'person'
left join firms f on f.contacts_id = c.id and c.type = 'firm'
where c.id = 42;

Here is an alternative way without a join:这是没有连接的另一种方法:

select 
  case when c.type = 'person' then
    (select name from people p where p.contacts_id = c.id)
  else
    (select name from firms f on f.contacts_id = c.id)
  end as name
from contacts c
where c.id = 42;

You see, there are many ways to address the problem.你看,有很多方法可以解决这个问题。 Just pick the one you find most readable.只需选择您认为最易读的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM