我需要为C#中的特定方法(使用NHibernate)执行原始SQL,并且我很难将查询合并到不同的表中,因为我几乎不使用ORM。在这种情况下,我正在查询其中的三个,我想从第二个查询的最后一行中的第一个简单选择的结果中使用offerId(而不是使用harcoded 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,但最后我会得到与数据库一样多的查询结果,这样会杀死性能,对吗?
由于
答案 0 :(得分: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
)
答案 1 :(得分: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)
答案 2 :(得分: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]
中的主键是id
。
答案 3 :(得分: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 JOIN
和JOIN
是等效的语法。