SQL:使用不同的where条件对表进行两次查询?

时间:2012-10-23 05:48:30

标签: mysql sql join

我现有的查询如下:

SELECT
       id,
       refid,
       action_id,
       action_type,
       co_user_id,
       cust_vend_id,
       Aes_decrypt(cust_vend_name, '".DBKEY."') AS cust_vend_name,
       Aes_decrypt(amount, '".DBKEY."')         AS amount,
       Aes_decrypt(action_date, '".DBKEY."')    AS action_date,
       Aes_decrypt(memo, '".DBKEY."')           AS memo,
       Aes_decrypt(trans_id, '".DBKEY."')       AS trans_id,
       part_id,
       polarity
FROM   generated_actions
INNER join
        generated_actions.action_id             AS action_id
    ON
        (generated_actions.action
WHERE  acc_type = 2
   AND acc_id = $ba_id
   AND reverse_id IS NULL
ORDER  BY action_id,
          Aes_decrypt(action_date, '".DBKEY."'),
          entry_datetime ;

但是对于它选择的每个记录,我需要它还从记录中返回另一列,否则将被排除(因为它的acc_id是'1'而不是'2')。因此我需要它来找到acc_id AS'帐户',其中action_id与它当前选择的记录相同,其中part_id ='3'。

查询将选择多个记录,但不会为其他条件的每个记录找到匹配项。在这种情况下,它仍然应该返回主记录,但是将null作为'accounts'的值。

我的替代方案是,使用我提供的查询,然后对每个结果,再次检查同一个表SELECT acc_id WHERE action_id = $ action_id AND part_id ='3'。我认为必须有一种方法可以在一个查询中执行此操作吗?

我正在使用MySQL。

2 个答案:

答案 0 :(得分:1)

SELECT
  main.id,
  main.refid,
  main.action_id,
  main.action_type,
  main.co_user_id,
  main.cust_vend_id,
  Aes_decrypt(main.cust_vend_name, '".DBKEY."')   AS cust_vend_name,
  Aes_decrypt(main.amount,         '".DBKEY."')   AS amount,
  Aes_decrypt(main.action_date,    '".DBKEY."')   AS action_date,
  Aes_decrypt(main.memo,           '".DBKEY."')   AS memo,
  Aes_decrypt(main.trans_id,       '".DBKEY."')   AS trans_id,
  main.part_id,
  main.polarity,
  other.acc_id                                    AS other_acc_id
FROM
  generated_actions        AS main
LEFT JOIN
  generated_actions        AS other
    ON  other.action_id = main.action_id
    AND other.part_id   = 3
WHERE
      main.acc_type = 2
  AND main.acc_id   = $ba_id
  AND main.reverse_id IS NULL 
ORDER  BY
  main.action_id,
  Aes_decrypt(main.action_date, '".DBKEY."'),
  main.entry_datetime
; 

这将表连接到它自己。这就好像有两张单独的表格副本。

因为你有两个副本,每个副本都需要它自己的名字。这就是AS mainAS other的作用,它只是为表格的每个引用提供了一个单独的名称。

LEFT JOIN就像一个内连接,除了它始终保持左侧表中的记录 - 即使它没有连接到右边表中的任何记录。

答案 1 :(得分:0)

这可以很容易地以procedure完成,但您也可以只执行多个批次。如果您提前知道所需的Part_ID,请考虑使用IN clause

潜在地,在你在IN子句中填充的子查询中获取所需的Part_ID。 e.g:

SELECT /*actual columns*/ *
FROM table
WHERE predicate_column IN (
    SELECT predicate_column
    FROM table
    WHERE known_column = $known_value
)