[英]How to make SELECT that “knows” which entity has more elements?
I have a simple database that has three tables ( company
, phone
, email
) which are related through the rules: 我有一个简单的数据库,其中包含三个通过规则关联的表( company
, phone
, email
):
Here is the MySQL code: Pastebin 这是MySQL代码: Pastebin
Let's suppose the following 2 cases: 让我们假设以下两种情况:
~ 〜
I would like to make a SELECT that returns the following: 我想做一个选择,返回以下内容:
Case 1 情况1
Company Phone E-mail
--------------------------------------------
Test Company 1111222 export@testco.co
Test Company 2222222 import@testco.co
Test Company 3333222
--------------------------------------------
Case 2 情况二
Company Phone E-mail
--------------------------------------------
Test Company 1111222 export@testco.co
Test Company 2222222 import@testco.co
Test Company sales@testco.co
--------------------------------------------
That SELECT should "know", for a given company, which entity has more elements ( phone
or email
) and then return a result where the number of rows is equal to number of elements from the entity with more elements ( phone
in case 1; email
in case 2). 对于给定的公司,该SELECT应该“知道”哪个实体具有更多元素( phone
或email
),然后返回结果,其中行数等于来自具有更多元素的实体中的元素数目 (在情况1中为phone
;在情况2中email
)。
I could not figure out how to do that. 我不知道该怎么做。 Here's the best I could do: Pastebin 这是我能做的最好的事情: Pastebin
This is a pain to do in MySQL, but it is possible. 这在MySQL中是很痛苦的事,但是有可能。 Here is the logic. 这是逻辑。 Enumerate the values for the emails and phones for each company. 枚举每个公司的电子邮件和电话的值。 Then aggregate these based on the company and sequence number: 然后根据公司和序列号汇总这些:
select ep.company, min(ep.email) as email, min(ep.phone) as phone
from ((select e.company, e.email, NULL as phone,
(@rne := if(@company = company, @rne + 1, if(@company := company, 1, 1)) ) as seqnum
from email e cross join
(select @rne := 0, @company := '') vars
order by e.company
) union all
(select p.company, NULL, p.phone,
(@rnp := if(@companyp = company, @rnp + 1, if(@companyp := company, 1, 1)) ) as seqnum
from phone p cross join
(select @rnp := 0, @companyp := '') vars
order by p.company
)
) ep
group by ep.company, ep.seqnum
order b ep.company, ep.seqnum;
The expression: 表达方式:
(@rne := if(@company = company, @rne + 1, if(@company := company, 1, 1)) ) as seqnum
for setting seqnum
is a way of safely using the variables in MySQL. 设置seqnum
是安全使用MySQL中变量的一种方法。 Note that MySQL does not guarantee the order of evaluation of expressions in a select, so the more natural: 请注意,MySQL不保证选择中表达式的求值顺序,因此更为自然:
@rne := if(@company = company, @rne + 1, 1), @company := company
may not work, because the second would be evaluated first. 可能不起作用,因为第二个优先。 This method with the nested assignment doesn't have this problem. 具有嵌套分配的此方法不存在此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.