简体   繁体   English

将两个SQL查询合而为一

[英]Making two SQL queries into one

How can i perform these two queries in one single query, so that it shows the eid that has more than 2 values and shows its eid as well? 我如何在一个查询中执行这两个查询,以便显示具有两个以上值的eid并显示其eid?

select eid, count(Edited_by.eid)
from Edited_by
group by eid;


select Editor.eid  
from Editor 
where ( select count(*) 
    from Edited_by 
    where Edited_by.eid=Editor.eid ) > 2;

UPDATE 更新


A predicate in the HAVING clause can operate on aggregate expressions. HAVING子句中的谓词可以对聚合表达式进行操作。 I think you may be looking for something like this: 我认为您可能正在寻找这样的东西:

SELECT t.eid
     , COUNT(t.eid) AS cnt
  FROM Edited_by t
 GROUP BY t.eid
HAVING COUNT(t.eid) > 2

Whoops. 哎呀 I entirely missed that the two queries were referencing two different tables. 我完全错过了这两个查询引用了两个不同的表的情况。

To also reference the Editor table, you could use the query above as an inline view. 要同时引用Editor表,您可以将上面的查询用作内联视图。

SELECT c.eid                  AS edited_by_eid
     , c.cnt                  AS cnt
     , IF(c.cnt>2,e.Eid,NULL) AS editor_eid
  FROM Editor e
  JOIN ( SELECT t.eid
              , COUNT(t.eid) AS cnt
           FROM Edited_by t
          GROUP BY t.eid
       ) c
    ON c.eid = e.Eid

FOLLOWUP 跟进

Q: "I want to get the result of BOTH queries by running one." 问: “我想通过运行一个查询来获得两个查询的结果。”

A: I'm not understanding exactly what you want to achieve. 答:我不太了解您要实现的目标。

To have two separate resultsets returned, you would need to run two separate statements. 要返回两个单独的结果集,您将需要运行两个单独的语句。 MySQL can return multiple resultsets from a stored procedure, for example, a procedure could execute the two queries. MySQL可以从存储过程返回多个结果集,例如,一个过程可以执行两个查询。 The client could process both resultsets (if that's supported and enabled in the client interface library.) That would be a "single statement" ( CALL my_procedure; ). 客户端可以处理两个结果集(如果客户端接口库中支持并启用了这两个结果集)。这将是“单个语句”( CALL my_procedure; )。

If you want to concatenate the results of two separate queries, you could use the UNION ALL set operator. 如果要连接两个单独查询的结果,可以使用UNION ALL set运算符。 Normally, I would return a discriminator column to distinguish which rows were returned by which query. 通常,我将返回一个区分符列以区分哪个查询返回了哪些行。 To do that, the number of columns and the datatypes of each column must match between the two queries. 为此,两个查询之间的列数和每列的数据类型必须匹配。

In the example you give, the query from the Editor table would need to return a dummy integer-type column in order to concatenate the two results. 在您给出的示例中,来自Editor表的查询将需要返回一个虚拟整数类型列,以将两个结果连接起来。

SELECT t.eid
     , COUNT(Edited_by.eid) AS cnt
  FROM Edited_by t
 GROUP BY t.eid
 UNION ALL
 SELECT e.eid
      , 0 AS cnt
   FROM Editor e
  WHERE ( SELECT COUNT(*)
            FROM Edited_by c
           WHERE c.eid=e.eid 
        ) > 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM