EXISTS IN查询怎么样?

时间:2012-11-26 17:07:55

标签: mysql

有人可以帮我这个,我有2张桌子

financeaccountcurrencymapping和ownedac​​count。

我想选择那些其领域为legalEntity_id的financeaccountcurrencymapping。

这是我到目前为止所拥有的。

SELECT 
FROM financeaccountcurrencymapping 
WHERE ownedAccount_id EXISTS IN (
                SELECT id 
                FROM ownedaccount 
                WHERE legalEntity_id = ??);

表格中的字段为:

'financeaccountcurrencymapping'

  • id
  • moneyCurrency
  • accountForCash_id
  • ownedAccount_id

'ownedac​​count'

  • ID
  • 名称
  • legalEntity_id
  • assetOrLiability
  • assetType
  • depositoryType
  • liabilityType
  • multipleCurrency
  • 货币
  • 描述

4 个答案:

答案 0 :(得分:4)

在这种情况下你不会使用EXISTS。单独使用就可以了。

SELECT 
FROM financeaccountcurrencymapping 
WHERE ownedAccount_id IN (SELECT id FROM ownedaccount WHERE legalEntity_id = ??);

答案 1 :(得分:1)

SELECT legalEntity_id
FROM financeaccountcurrencymapping 
WHERE ownedAccount_id IN (
                SELECT id 
                FROM ownedaccount 
                WHERE legalEntity_id = ??);

答案 2 :(得分:1)

你原来的查询非常接近。您只需删除EXISTS,就像这样:

SELECT *
FROM financeaccountcurrencymapping 
WHERE ownedAccount_id IN (
                SELECT id 
                FROM ownedaccount 
                WHERE legalEntity_id = ??);

或者,您可以使用JOIN编写此查询以获得相同的有效结果。

SELECT f.*
FROM financeaccountcurrencymapping AS f 
INNER JOIN ownedaccount AS o ON (f.id = o.ownedAccount_id) 
WHERE o.legalEntity_id = ??;

答案 3 :(得分:1)

如果你真的想使用EXISTS或想看一个如何使用EXISTS的例子,我认为以下内容可行。我个人可能会改用IN。

SELECT 
FROM financeaccountcurrencymapping as f
WHERE EXISTS (SELECT id 
              FROM ownedaccount 
              WHERE f.ownedAccount_id = id AND legalEntity_id = ??);