我们在MySQL数据库中有3个表,
行业表
行业
| pkIndustryID | industryName |
|--------------|------------------------|
| 1 | Accounting and Finance |
| 2 | Legal |
| 3 | Health Care |
用户表
用户
| pkUserID | UserName |
|----------|------------------|
| 1 | Saurabh Sharma |
| 2 | Avinash Panday |
| 3 | Mrinal Chaudahry |
用户和行业的关系表
provider_industries
| pkProviderindustryID | fkUserID | fkIndustryID |
|----------------------|----------|--------------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 1 |
| 6 | 3 | 2 |
| 7 | 3 | 3 |
现在我的问题是我想要所有用户的用户,但任何用户都不应该重复。如何使用单个SQL查询实现此目的?
预期结果
| pkProviderindustryID | fkUserID | fkIndustryID |
|----------------------|----------|--------------|
| 1 | 1 | 1 |
| 4 | 2 | 2 |
| 7 | 3 | 3 |
我不希望重复用户和行业! 结果应显示具有不同行业的不同用户。其中任何一个都不应重复使用InsustryID或userID
任何帮助将不胜感激! 谢谢!!!
答案 0 :(得分:1)
试试这个
select p.pkProviderindustryID, u.fkUserID, i.fkIndustryID
from industries i
join provider_industries p on i.pkIndustryID =p.fkIndustryID
join users u on p.fkUserID = u.pkUserID
group by u.pkUserID
答案 1 :(得分:0)
仅由您的用户分组
即:
select users.pkUserID, users.UserName
from provider_industries
inner join users
on users.pkUserID = provider_industries.fkUserID
group by users.pkUserID, users.UserName
如果您想添加行业,则需要使用min()/ max() 例如
select users.pkUserID, users.UserName, min(industryName)
from provider_industries
inner join users
on users.pkUserID = provider_industries.fkUserID
inner join industries
on industries.pkIndustryID = provider_industries.pkProviderindustryID
group by users.pkUserID, users.UserName