如何创建双查询SQL?

时间:2015-05-11 15:28:24

标签: sql

我想知道如何接收一个结果,并且通过该结果,将其提供给新查询。这就是我现在所拥有的:

   SELECT A.id_buc               AS BUC,
        A.id_promotor_ALTAIR     AS EJECUTIVO
     FROM cl_cliente       A
    WHERE A.id_buc=(SELECT B.id_contrato       AS CONTRATO,
                           B.id_buc            AS BUC,
                           B.fec_apertura      AS FECHA
                         FROM el_contrato       B
                        WHERE B.id_contrato IN (80121221158));

但是这个查询会让我错误。

3 个答案:

答案 0 :(得分:2)

您的查询中存在两个问题:

  1. 如果内部查询有两个或更多结果,则应使用IN而不是=
  2. 内部查询应该只返回一个列,此列的值将作为要检索的字段的过滤器。
  3. 因此,您的查询应如下所示:

    SELECT A.id_buc          AS BUC,
        A.id_promotor_ALTAIR AS EJECUTIVO
    FROM cl_cliente A
    WHERE A.id_buc IN (SELECT B.id_buc
                    FROM el_contrato B
                    WHERE B.id_contrato IN (80121221158));
    

    但是这个查询非常糟糕,而且表现可怕。如果使用JOIN在单个查询中重写它会更好,并且您可以根据需要检索两个表的数据:

    SELECT A.id_buc             AS BUC,
           A.id_promotor_ALTAIR AS EJECUTIVO,
           B.id_contrato        AS CONTRATO,
           B.id_buc             AS BUC,
           B.fec_apertura       AS FECHA
    FROM cl_cliente A
         INNER JOIN el_contrato B ON A.id_buc = B.id_buc
    WHERE B.id_contrato IN (80121221158);
    

答案 1 :(得分:1)

也许您正在尝试创建内联视图并将其加入另一个表?

SELECT A.id_buc AS BUC,
       A.id_promotor_ALTAIR AS EJECUTIVO, 
       B.*
FROM cl_cliente  A
INNER JOIN (SELECT B.id_contrato AS CONTRATO,
                   B.id_buc            AS BUC,
                   B.fec_apertura      AS FECHA
            FROM el_contrato       B
            WHERE B.id_contrato IN (80121221158)) B
    ON A.id_buc= B.ID_BUC

或者您可能只需要learn how to use Joins...

SELECT A.id_buc              AS BUC,
       A.id_promotor_ALTAIR  AS EJECUTIVO,
       B.id_contrato         AS CONTRATO,
       B.id_buc              AS el_contrato_BUC,
       B.fec_apertura        AS FECHA
FROM cl_cliente A
INNER JOIN el_contrato B
  ON A.id_buc= B.ID_BUC  
WHERE B.id_contrato IN (80121221158)

答案 2 :(得分:0)

@xQbert

谢谢,它只是用这个:

        

SELECT A.id_buc              AS BUC,
        A.id_promotor_ALTAIR  AS EJECUTIVO,
        B.id_contrato         AS CONTRATO,
        B.id_buc              AS el_contrato_BUC,
        B.fec_apertura        AS FECHA
 FROM cl_cliente A
 INNER JOIN el_contrato B
   ON A.id_buc= B.ID_BUC
WHERE B.id_contrato IN (80121221158)