1

I have a table called accounts

I have fields called

id  
provider
type
account_name 

they are structured as

id - int(12)
provider -int(12)
type - int(12)
account_name - Varchar(25)

I think a join or subquery could work but cant get it work The aim is i want to display providers that have both type=2 and type=5 ORDER By account_name

eg shows companies that sell both real estate and loans

Select * from accounts WHERE type = 2 and type=5

I know the above doesnt work but its kind the mindset that i need. Id appreciate any help in getting this working.

The mysql output result should look like this in a single line.

Eg

Provider Account_Name1(this matched 2) Account_Name2(Matched 5) Johnson - Johnson Real Estate - Johnson Loans

4

2 回答 2

4

这应该查找同时具有id2 和 5 的提供程序:

select  provider
from    accounts
where   id in (2,5)
group by
        provider
having  count(distinct id) = 2
于 2013-06-18T11:13:30.537 回答
0
select distinct acc2.provider,acc2.account_name,acc5.account_name
from accounts acc2 inner join accounts acc5 on acc2.provider=acc5.provider
where acc2.type = 2 and acc5.type = 5

这有点假设不会有重复provider/type组合。例如,一个提供者具有多行具有相同的type. 事实上,distinct如果数据符合该要求,则没有必要。

顺便说一句,这是一张有点奇怪的桌子,虽然我不知道完整的故事。这似乎是用于将提供者与帐户类型相关联的表。并且每个提供者和帐户类型的关联都可以有一个 Account_Name。我认为这会更好地用 3 个表来表示。

TABLE Provider (
   ID INT PK
   Name VARHCAR(50)
)

TABLE AccountType (
   ID INT
   AccountType VARCHAR(50)
)

TABLE ProviderAccountType (
   ProviderID PK FK
   AccountTypeID PK FK
   AccountName VARCHAR(50)
)
于 2013-06-18T12:06:21.247 回答