c# - 使用 2 个表之间的可选/条件联接进行查询

标签 c# mysql .net linq join

ResourceTranslation
--------------------------------------------
ID                          binary(16)      |
ShortStringResourceID       binary(16)      |
LocaleName                  varchar(50)     |
TranslatedText              text            |
--------------------------------------------


ShortStringresource
--------------------------------------------
ID                          binary(16)      |
PrimaryLocaleName           varchar(50)     |
ContentText                 varchar(255)    |
--------------------------------------------

我想在 LINQ to SQL 中实现与以下 SQL 等效的功能:

SELECT (CASE p.PrimaryLocaleName WHEN 'en-GB' THEN p.ContentText ELSE t.ContentText END)
FROM shortstringresource p 
     LEFT OUTER JOIN resourcetranslation t ON t.ShortStringResourceID = p.ID 
WHERE p.ContentText = "Question 1 English Text"
AND (p.PrimaryLocaleName = 'en-GB' OR t.LocaleName = 'en-GB')
LIMIT 1;

或者将以下 2 个查询加入到 1 个查询中:

var qry1 = (from p in I18nObjects.ShortStringResources
            where (p.PrimaryLocaleName == "en-GB" && p.ContentText == "my text")
            select p.ContentText);

var qry2 = (from t in I18nObjects.ResourceTranslations
           where t.LocaleName == "en-GB" 
           join p in I18nObjects.ShortStringResources on t.ShortStringResourceID equals p.ID
           select t.TranslatedText);

最佳答案

您可能需要在选择之前考虑订购。

var results = (from p in ShortStringResources 
   join t in ResourceTranslations on p.ID equals t.ShortStringResourceID into xy
   from x in xy.DefaultIfEmpty()
   where p.ContentText == "Question 1 English Text" &&
        (p.PrimaryLocaleName == "en-GB" || x.LocaleName == "en-GB")
   select new {
      newField = p.PrimaryLocaleName == "en-GB"? p.ContentText : x.ContentText
   }).ToList().Take(1);

关于c# - 使用 2 个表之间的可选/条件联接进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15229443/

相关文章:

c# - 使用 Linq 和 C#,尝试从由两个内部列表分组的主项列表中获取两个列表

mysql系统命令

mysql - 无效的默认值

mysql - 在 Linux 中使用 MySQL "error: unknown type name ‘uint’ 编译 C 项目时出错

.net - 比较两个列表以获取同时出现在两个列表中的对象

c++ - 如何在退出时调试 CorExitProcess 中的访问冲突 0xC0000005?

.net - 不可变对象(immutable对象)的线程安全性如何?

c# - 表模块和事务脚本之间的区别

c# - 如何使用 ado.net 从 mssql 中选择数据

c# - 检查控制计时器的线程的状态