按列结合mysql查询

时间:2014-09-08 17:03:03

标签: mysql sql

有没有以列方式组合mysql查询?我有以下查询

select  count(ticket_id) as numInProgress from ost_ticket where status
 = 'in progress' and topic_id not in (select topic_id from ost_org_site_map)

 select  count(ticket_id) as numAssigned from ost_ticket where status =
 'open' and topic_id not in (select topic_id from ost_org_site_map)

我试图以下面的格式得到结果

---numInProgress | numAssigned---
            2    |     8
---------------------------------

3 个答案:

答案 0 :(得分:1)

只需在select语句中将它们用作子查询,例如

SELECT ($statement1$),($statement2$)

或您的查询:

SELECT (select count(ticket_id) as numInProgress from ost_ticket where status = 'in progress' and topic_id not in (select topic_id from ost_org_site_map)) as numInProgress ,(select count(ticket_id) as numAssigned from ost_ticket where status = 'open' and topic_id not in (select topic_id from ost_org_site_map)) as numAssigned;

答案 1 :(得分:0)

你可以试试这个:

SELECT (select count(ticket_id) as numInProgress 
        from ost_ticket where status = 'in progress' 
        and topic_id not in (select topic_id from ost_org_site_map)),
       (select count(ticket_id) as numAssigned 
        from ost_ticket where status = 'open' 
        and topic_id not in (select topic_id from ost_org_site_map));

即组合两个查询以在select语句中生成子查询。

答案 2 :(得分:0)

也许这就是:

SELECT sum(CASE OT.status when 'in progress' ,1,0) as numInProgress,
       sum(CASE OT.status when 'open' ,1,0) as numAssigned 
FROM ost_ticket OT
LEFT JOIN OST_ORG_SITE_MAP OSM
 ON OT.topic_Id =OSM.Topic_ID
WHERE OT.status in ('in progress', 'open')
  and OSM.Topic_ID is null

左连接允许我们在topic_Id上加入OST_TICKET和OST_ORG_SITE_MAP。当site_map表中没有主题ID时,我们有一个等同于topic_Id不在...

我们将状态结合起来只查找正在进行和打开状态,我们使用状态语句来确定需要计算的内容。由于count将返回1和0的值,我们需要使用sum来代替1和0。