1

我现有的查询如下所示:

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 'account',其中 action_id 与其当前选择的记录相同,part_id = '3'。

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

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

我正在使用 MySQL。

4

2 回答 2

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就像一个内部连接,除了它始终保留左侧表中的记录 - 即使它不连接到右侧表中的任何记录。

于 2012-10-23T06:00:24.807 回答
0

这可以很容易地作为一个过程来完成,但您也可以只连续执行多个批次。考虑一下,如果您提前知道所需的 Part_ID,请使用IN 子句

潜在地,在 IN 子句中填充的子查询中获取您需要的 Part_ID。例如:

SELECT /*actual columns*/ *
FROM table
WHERE predicate_column IN (
    SELECT predicate_column
    FROM table
    WHERE known_column = $known_value
)
于 2012-10-23T05:58:19.833 回答