基础查询-SQL和Linq相互化

内容纲要

[TOC]

SELECT

SELECT 语句用于从表中选取数据,是 SQL 最基本的操作之一。

通过 SELECT 查询的结果被存储在一个结果表中(称为结果集)。

SQL SELECT 语法

只查询某个列的数据:

SELECT [列名称] FROM [表名称]

查询所有列的数据

SELECT * FROM [表名称]

SQL

查询所有数据

SELECT * FROM categories

查询一列或多列

SELECT category_id,category_name FROM categories

查询表达式

            var list = from categories in context.Categories
                       select new
                       {
                           categories.CategoryId,
                           categories.CategoryName
                       };

            var lists = from categories in context.Categories
                        select categories;

查询语句

            var list = context.Categories.Select(categories =>
            new
            {
                categories.CategoryId,
                categories.CategoryName
            });
            var lists = context.Categories.Select(categories => categories);

SQL SELECT DISTINCT 语句

DISTINCT 可以去除查询结果集中完全相同的项,只有每一个列中每一个数据都相同,才能被认为是“完全相同”。

可在 categories 表中添加相同数据的项进行测试(除主键外相同)。

SQL

SELECT DISTINCT category_id,category_name FROM categories

查询表达式

            var dislist = list.Distinct();

            var dislist2 = (from categories in context.Categories
                            select new
                            {
                                categories.CategoryId,
                                categories.CategoryName
                            }).Distinct();

查询语句

            var dislist = list.Distinct();
            var dislist2 = context.Categories.Distinct().Select(categories =>
              new
              {
                  categories.CategoryId,
                  categories.CategoryName
              });

WHERE 和 操作符

用于条件筛选。

操作符 描述
= 等于
<> 不等于
> 大于
< 小于
>= 大于等于
<= 小于等于
BETWEEN 在某个范围内
LIKE 搜索某种模式

注释:在某些版本的 SQL 中,操作符 <> 可以写为 !=。

BETWEEN 和操作符

BETWEEN ... ANDBETWEEN ... OR

C# 中可以使用 &&||表示。

SQL

SELECT [列名称] FROM [表名称] WHERE [列] [运算符] [值]
SELECT
    category_id,
    category_name 
FROM
    categories 
WHERE
    BETWEEN category_id > 1 
    AND category_id < 5

查询表达式

            var list3 = from categories in context.Categories
                        where categories.CategoryId > 1 && categories.CategoryId < 5
                        select categories;

查询语句

            var list3 = context.Categories.Where(x => x.CategoryId > 1 && x.CategoryId < 5);

LIKE 和通配符

在 SQL 中,可使用以下通配符:

通配符 描述
% 替代一个或多个字符
_ 仅替代一个字符
[charlist] 字符列中的任何单一字符
[^charlist]或者[!charlist] 不在字符列中的任何单一字符

SQL

SELECT * FROM categories WHERE  category_name like 'B%'

查询表达式

            var list4 = from categories in context.Categories
                        where categories.CategoryName.StartsWith("B")
                        select categories;

不能直接使用 %。

查询语句

            var list4 = context.Categories.Where(x => x.CategoryName.StartsWith("B"));

Linq 只有 Startwith 、 Endwith 和 Contains,没有其它通配符。

而 EF中提供了 EF.Functions.Like() 来进行通配符操作。

例如:

            var list5 = from categories in context.Categories
                        where EF.Functions.Like(categories.CategoryName,"B_")
                        select categories;
            var list5 = context.Categories.Where(x => EF.Functions.Like(x.CategoryName, "B_"));

更多通配符操作,请自行了解 EF.Functions.Like()

ORDER BY 排序

SQL

SELECT * FROM categories ORDER BY category_id

C#

            var list6 = (from categories in context.Categories
                         select categories).OrderBy(c => c.CategoryId);

            var list7 = from categories in context.Categories
                        orderby categories.CategoryId
                        select categories;
            var list6 = context.Categories.OrderBy(x => x.CategoryId).ToList();

            var list7 = context.Categories.ToList().OrderBy(x=>x.CategoryId);

TOP

PostgreSQL 中没有 TOP,可以使用 OFFSET、LIMIT 代替。

SELECT select_list
    FROM table_expression
    [ ORDER BY ... ]
    [ LIMIT { number | ALL } ] [ OFFSET number ]

Top(5) 的表达

SELECT * FROM test ORDER BY test  LIMIT 5

或者

SELECT * FROM test OFFSET 0 LIMIT 5

一般与 Order by 一起使用

SELECT * FROM test ORDER BY test OFFSET 5 LIMIT 5

LIMIT ALL 的效果和省略LIMIT子句一样,例如下面的 SQL 或获取全部数据。

SELECT * FROM test LIMIT ALL   --等价 SELECT * FROM test

C#代码中,则相应使用 Take 、 Skip。

            var list = (from c in context.UserRoles
                        select c).Skip(0).Take(5);
            var list = context.UserRoles.Skip(0).Task(5);

例外:

T-SQL 中的 Top(1) ,在 PostgreSQL 中,可以表示

SELECT * FROM test LIMIT 1

而 C# 表示:

            var list00 = (from c in context.UserRoles
                         select c).First();
            var list01 = (from c in context.UserRoles
                          select c).FirstOrDefault();
            var list02 = (from c in context.UserRoles
                          select c).Take(1);

            var list10 = context.UserRoles.First();
            var list11 = context.UserRoles.FirstOrDefault();
            var list12 = context.UserRoles.Take(1);

可以使用 First() 或 FirstOrDefault() 返回查询结果中的第一条数据,方法体中不加条件,相当于 Top(1)

TakeWhile 和 SkipWhile

TakeWhile

运行查询,直到某一条件成立才停止获取;即当条件成立时,才会停止。

SkipWhile

运行查询,直到某一条件成立才停止跳过;即当条件成立时,才会开始。

In

与 Where 一起使用,表示符合条件中的一个。

SELECT * FROM test WHERE test IN ('1','2')
SELECT * FROM test WHERE test NOT IN ('1','2')

C# 中用 Contains 表示

            string[] item = new string[] { "a","b","c"};
            var list = from c in context.UserRoles
                       where item.Contains(c.RoleId)
                       select c;
            var list2 = context.UserRoles.Where(x => item.Contains(x.RoleId));

Alias(as)

SQL 中,可以给查询的列设置别名,例如

SELECT test as ttttt FROM test 

C#中,应该无直接如此的操作。

不过,很多操作形式最后生成的 SQL 都会出现 AS。

EXISTS 和 NOT EXISTS

SQL C#
IN Contains
EXISTS Any
NOT EXISTS All

EXISTS

判断子查询中是否有结果集返回,如果有即为 TRUE。

子查询中应当有 where 等条件

SELECT * FROM test EXISTS ({子查询})

EXISTS 并不关注 子查询中返回了什么、返回了多少结果集,它只判断有没有结果返回(查询返回的结果集,行数>0)。

例如

SELECT * FROM test EXISTS (SELECT 1 FROM test where test == "a")

C#

使用 .Any()

            var list = from s in context.UserRoles
                       where (from c in context.UserRoles
                              select c).Any()
                       select s;
            var list2 = context.UserRoles.Where(x => context.UserRoles.Any());

Any() 中也可以加条件

            var list = from s in context.UserRoles
                       where (from c in context.UserRoles
                              select c).Any(x => x.RoleId != "x")
                       select s;
            var list2 = context.UserRoles.Where(x => context.UserRoles.Any(x => x.RoleId != "x"));

NOT EXISTS

无结果集返回则为,没有返回则为 TRUE。

子查询中应当有 where 等条件判断。

Linq 的 拓展方法 All,表示每一个元素是否都符合条件。返回 Bool。。

            var list = from s in context.UserRoles
                       where context.UserRoles.All(x=>x.RoleId=="a")
                       select s;
            var list2 = context.UserRoles.Where(x => context.UserRoles.All(x => x.RoleId == "x"));

In 比 EXISTS 的速度快。

点赞
  1. purchase luvox说道:

    I am commenting to let you know of the fine encounter my cousin's daughter experienced reading your site. She even learned many issues, not to mention what it's like to have a wonderful giving mindset to have many people quite simply grasp chosen hard to do subject areas. You really exceeded our expectations. Many thanks for giving the insightful, healthy, educational and as well as easy thoughts on the topic to Jane.

  2. desyrel buy说道:

    I precisely had to appreciate you all over again. I'm not certain the things I might have done in the absence of the actual hints discussed by you concerning such field. It actually was a real difficult condition for me personally, but discovering a new professional fashion you handled it forced me to jump for delight. I'm just happier for the guidance and as well , have high hopes you comprehend what a powerful job you're carrying out instructing most people through your blog. I am sure you've never encountered all of us.

  3. I like the efforts you have put in this, thank you for all the great content.

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!