SQL简单查询

标签 sql mysql

我有下表Persons_Companies,它显示了这些人所知道的个人和公司之间的关系:

PersonID  |  CompanyID

   1             1
   2             1
   2             2
   3             2
   4             2

假设公司 1 =“Google”,公司 2 =“Microsoft”,我想知道查询会得到以下结果:

PersonID  |  Microsoft    |    Google

   1             0                1
   2             1                1
   3             1                0
   4             1                0

直到此刻我有类似的东西:

select PersonID,
case when CompanyID=1 then 1 else 0
end as Google,
case when EmpresaID=2 then 1 else 0
end as Microsoft
from Persons_Companies

我的问题是了解这两家公司的人,我无法想象这个查询怎么可能。

什么是 SQL 查询?

最佳答案

select PersonID,
case when EXISTS (
   SELECT 1 
   FROM Persons_Companies pc1 
   WHERE pc.PersonID = pc1.PersonID and pc1.CompanyID = 1 ) then 1 else 0
end as Google,
case when EXISTS (
   SELECT 1 
   FROM Persons_Companies pc2
   WHERE pc.PersonID = pc2.PersonID and pc2.CompanyID = 2 ) then 1 else 0
end as Microsoft
from Persons_Companies pc

关于SQL简单查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2493285/

相关文章:

php - 多功能 PHP 代码 - 似乎无法让它正常工作

mysql - Query1 与 Query2 连接,但 Query2 使用 Query1 的结果,如何仅使用 1 个查询来做到这一点?

mysql - date_format(from_unixtime()) 子选择非常慢

SQL Server 2012 Management Studio 没有 mdf 文件的附加选项

php - 需要更新 mysql 查询以选择预订酒店房间或任何东西的日期范围

mysql - SQL : Select row where a column of this row does't match with a certain value

mysql - sql查询选择两列中具有相同id但不同值的记录

php - 使用 PHP 和 MySQL 为用户提供不同的访问级别

c# - 如何在连接第三个表时对列表进行外连接

mysql - sql中的字母大小写转换