[英]Mysql Join Two Queries
I have two queries: 我有两个问题:
SELECT opr, COUNT(*) FROM table WHERE field = 'YES' GROUP BY opr
SELECT opr, MAX(category) FROM table WHERE field = 'NO' GROUP BY opr
So basically in the first query I am getting the number of transactions a user makes. 所以基本上在第一个查询中我得到了用户进行的交易数量。 In the second query I am getting a category that all of those transactions fall under.
在第二个查询中,我得到一个所有这些交易都属于的类别。 I don't want to get all categories for each transaction they made, just the Max of the category field so that I have one entry per operator.
我不想为他们所做的每笔交易获得所有类别,只需要获取类别字段的最大值,以便每个运营商都有一个条目。
Until now, I have been catching both result sets in separate arrays and the looping through both arrays to get the complete opr->picks->category. 到目前为止,我一直在单独的数组中捕获两个结果集,并在两个数组中循环以获得完整的opr-> picks->类别。
This doesn't always work it sometimes associates the wrong category to the wrong operator. 这并不总是有效,它有时会将错误的类别与错误的运算符相关联。
Is there a way to combine these two queries into one, so that I get the operator and picks, then the MAX(category)? 有没有办法将这两个查询合并为一个,以便我得到运算符和选择,然后是MAX(类别)? The issue is that the conditions for each query are different on the field column.
问题是每个查询的条件在字段列上是不同的。
SELECT opr,
COUNT(CASE WHEN field = 'YES' THEN 1 END) AS number_of_transactions,
MAX(CASE WHEN field = 'NO' THEN category END) AS category
FROM table
GROUP BY opr ;
The above logic can be attained in one query by using CASE
通过使用
CASE
可以在一个查询中获得上述逻辑
SELECT opr, COUNT(CASE WHEN `field` = 'YES' THEN opr END) as `count`,
MAX(CASE WHEN `field` = 'NO' THEN category END) as `max`
FROM table GROUP BY opr
Just add it in: 只需添加:
SELECT opr,count(*), MAX(category) FROM table WHERE field = 'YES' GROUP BY opr
You might also be able to drop it from 2 queries to 1 with this: 您也可以使用以下命令将其从2个查询中删除为1:
SELECT opr,count(*), MAX(category), field FROM table GROUP BY opr, field
even faster on the processor, use a sum bool: 在处理器上更快,使用sum bool:
select
opr,
sum(field='yes') as transactions,
max(if(field='no',category, null)) as category
from table
group by opr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.