2

我需要为 C# 中的特定方法(否则使用 NHibernate)执行原始 SQL,并且我正在努力将查询合并到不同的表,因为除了 ORM 之外我几乎不使用。在这种情况下,我要查询其中的三个,并且我想使用第二个查询最后一行中第一个简单选择的结果中的 offerId(而不是使用硬编码的 1003)

SELECT * FROM [OFFER]
WHERE CampaignId = 1 AND Processed Is NULL

SELECT [BANK].* FROM [BANK]
INNER JOIN [REMINDER]
ON [BANK].personId = [REMINDER].personId AND [BANK].isCurrent = 1
WHERE [REMINDER].offerId = 1003

我曾尝试执行第一个查询,然后使用 foreach,但最终我会对数据库进行与结果一样多的查询,因此它会降低性能,对吗?

谢谢

4

4 回答 4

1

数据以某种方式联系在一起。这意味着那里必须有一个外键。那你应该去内部连接。

SELECT [BANK].* [OFFER].* FROM [BANK]
INNER JOIN [REMINDER]
  ON [BANK].personId = [REMINDER].personId AND [BANK].isCurrent = 1
INNER JOIN [OFFER]
  ON [REMINDER].offerId = [OFFER].id
WHERE [OFFER].CampaignId = 1 AND [OFFER].Processed Is NULL

这是假设中的主键[OFFER]is id

于 2013-10-03T14:00:00.023 回答
1
SELECT [BANK].* FROM [BANK]
INNER JOIN [REMINDER]
ON [BANK].personId = [REMINDER].personId AND [BANK].isCurrent = 1
WHERE [REMINDER].offerId in
(
SELECT offerId  FROM [OFFER]
WHERE CampaignId = 1 AND Processed Is NULL
)
于 2013-10-03T13:55:41.810 回答
1

使用IN谓词:

SELECT [BANK].* 
FROM [BANK]
INNER JOIN [REMINDER] ON [BANK].personId = [REMINDER].personId 
WHERE [BANK].isCurrent = 1
  AND [REMINDER].offerId IN (SELECT offerId FROM [OFFER]
                             WHERE CampaignId = 1 AND Processed Is NULL)
于 2013-10-03T13:55:50.670 回答
0

这是最直接的翻译,可能最容易理解原始的两个查询:

SELECT [BANK].* FROM [BANK]
INNER JOIN [REMINDER]
ON [BANK].personId = [REMINDER].personId AND [BANK].isCurrent = 1
WHERE [REMINDER].offerId IN (

  SELECT OfferId FROM [OFFER]
  WHERE CampaignId = 1 AND Processed Is NULL

)

您还可以使用JOIN语法:

SELECT [BANK].*
FROM [BANK]
     JOIN [REMINDER] ON [BANK].personId = [REMINDER].personId
                          AND [BANK].isCurrent = 1
     JOIN [OFFER] ON [REMINDER].OfferId = [OFFER].OfferId
WHERE [OFFER].CampaignId = 1 AND [OFFER].Processed Is NULL

请注意,INNER JOINandJOIN是等效的语法。

于 2013-10-03T13:55:57.203 回答