加入两个选择的结果 - mysql

时间:2014-04-27 12:55:54

标签: mysql join

我有两个选择查询:

SELECT Name as CategoryName FROM providerscategories where ID in(
Select catId from provider_in_category 
where providerUsername = 'a' group by providerUsername
);

另一个是:

SELECT Username, providerName from serviceproviders where Username in(
SELECT providerUsername from usedproviders where Username='Admin')

基本上它的作用是从usedproviders表中的Username从usedProviders获取providerName,然后根据结果获取提供者的UserName和providerName。 然后我想检查此提供程序所在的类别并获取此类别名称,并将其添加到该类别的UserName和providerName。

这是一个sql小提琴链接:SQL Fiddle

所需的结果集是:

  

用户名| ProviderName |类别名称

2 个答案:

答案 0 :(得分:1)

行。让我们从这里开始......以下问题的哪个部分问题无法解决...

SELECT sp.*
     , up.username
     , c.name
     , pc.catid
  FROM usedproviders up
  JOIN serviceproviders sp
    ON sp.username = up.providerusername
  JOIN provider_in_category pc
    ON pc.providerusername = up.providerusername
  JOIN providerscategories c
    ON c.id = pc.catid
 WHERE up.username = 'Admin';
+----------+--------------+----------+--------------+-------+
| Username | providerName | username | name         | catid |
+----------+--------------+----------+--------------+-------+
| a        | providerA    | Admin    | CategoryName |     1 |
| b        | providerB    | Admin    | CategoryName |     1 |
+----------+--------------+----------+--------------+-------+

答案 1 :(得分:0)

这是你可以做的

select 
sp.Username,
sp.providerName,
Name
from serviceproviders sp 
left join
(
  select
  usedproviders.ProviderUsername ,
  providerscategories.Name
  from 
  provider_in_category pic
  inner join 
  usedproviders on usedproviders.ProviderUsername = pic.providerUsername
  inner join 
  providerscategories on providerscategories.ID = pic.catId
  where 
  usedproviders.ProviderUsername = 'a'
  AND usedproviders.Username = 'admin'
  group by usedproviders.ProviderUsername
)t
on sp.Username = t.ProviderUsername

<强> DEMO

我看到你正在使用admina过滤数据,所以如果你不想看到第二条记录为NULL,那么改为LEFTJOIN只要让INNER加入第一部分。

此外,如果您不想要过滤器,则删除where子句并列出所有数据。

DEMO