SQL Joins with C# LINQ

There are Different Types of SQL Joins which are used to query data from more than one tables. In this article, I would like to share how joins work in LINQ. LINQ has a JOIN query operator that provide SQL JOIN like behavior and syntax. Let's see how JOIN query operator works for joins. This article will explore the SQL Joins with C# LINQ.

  1. INNER JOIN

  2. LEFT OUTER JOIN

  3. CROSS JOIN

  4. GROUP JOIN

The JOIN query operator compares the specified properties/keys of two collections for equality by using the EQUALS keyword. By default, all joins queries written by the JOIN keyword are treated as equijoins.

LINQ PAD for running and debugging LINQ Query

I am a big fan of LINQ Pad since it allow us to run LINQ to SQL and LINQ to Entity Framework query and gives the query output. Whenever, I need to write LINQ to SQL and LINQ to Entity Framework query then, I prefer to write and run query on LINQ PAD. By using LINQ PAD, you can test and run your desired LINQ query and avoid the head-ache for testing LINQ query with in Visual Studio. You can download the LINQ Pad script used in this article by using this link.

In this article, I am using LINQ PAD for query data from database. It is simple and useful. For more help about LINQ PAD refer the link. You can download the database script used in this article by using this link. Suppose we following three tables and data in these three tables is shown in figure.

INNER JOIN

Inner join returns only those records or rows that match or exists in both the tables.

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new{ od.OrderID,
  2. pd.ProductID,
  3. pd.Name,
  4. pd.UnitPrice,
  5. od.Quantity,
  6. od.Price,
  7. }).ToList();

LINQ Pad Query

INNER JOIN among more than two tables

Like SQL, we can also apply join on multiple tables based on conditions as shown below.

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID join ct in dataContext.tblCustomers on od.CustomerID equals ct.CustID orderby od.OrderID select new{ od.OrderID,
  2. pd.ProductID,
  3. pd.Name,
  4. pd.UnitPrice,
  5. od.Quantity,
  6. od.Price,
  7. Customer=ct.Name//define anonymous type Customer
  8. }).ToList();

LINQ Pad Query

INNER JOIN On Multiple Conditions

Sometimes, we required to apply join on multiple coditions. In this case, we need to make two anonymous types (one for left table and one for right table) by using new keyword then we compare both the anonymous types.

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID join ct in dataContext.tblCustomers on new{a=od.CustomerID,b=od.ContactNo} equals new{a=ct.CustID,b=ct.ContactNo} orderby od.OrderID select new{ od.OrderID,
  2. pd.ProductID,
  3. pd.Name,
  4. pd.UnitPrice,
  5. od.Quantity,
  6. od.Price,
  7. Customer=ct.Name//define anonymous type Customer
  8. }).ToList();

LINQ Pad Query

NOTE
  1. Always remember, both the anonymous types should have exact same number of properties with same name and datatype other wise you will get the compile time error "Type inferencce failed in the call to Join".

  2. Both the comparing fields should define either NULL or NOT NULL values.

  3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above fig.

LEFT JOIN or LEFT OUTER JOIN

LEFT JOIN returns all records or rows from left table and from right table returns only matched records. If there are no columns matching in the right table, it returns NULL values.

In LINQ to achieve LEFT JOIN behavior, it is mandatory to use "INTO" keyword and "DefaultIfEmpty()" method. We can apply LEFT JOIN in LINQ like as :

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductIDinto t from rt in t.DefaultIfEmpty() orderby pd.ProductID select new{//To handle null values do type casting as int?(NULL int)
  2. //since OrderID is defined NOT NULL in tblOrders
  3. OrderID=(int?)rt.OrderID,
  4. pd.ProductID,
  5. pd.Name,
  6. pd.UnitPrice,
  7. //no need to check for null since it is defined NULL in database
  8. rt.Quantity,
  9. rt.Price,
  10. }).ToList();

LINQ Pad Query

CROSS JOIN

Cross join is a cartesian join means cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records or rows that are multiplication of record number from both the tables means each row on left table will related to each row of right table.

In LINQ to achieve CROSS JOIN behavior, there is no need to use Join clause and where clause. We will write the query as shown below.

C# Code

  1. var q = from c in dataContext.Customers from o in dataContext.Orders select new{ c.CustomerID,
  2. c.ContactName,
  3. a.OrderID,
  4. a.OrderDate
  5. };

LINQ Pad Query

GROUP JOIN

Whene a join clause use an INTO expression, then it is called a group join. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. If right collection has no matching elements with left collection then an empty array will be produced.

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductIDinto t orderby pd.ProductID
  2. select new
  3. {
  4. pd.ProductID,
  5. pd.Name,
  6. pd.UnitPrice,
  7. Order=t
  8. }).ToList();

LINQ Pad Query

Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.

GROUP JOIN As SubQuery

We can also use the result of a GROUP JOIN as a subquery like as:

C# Code

  1. var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductIDinto t from rt in t where rt.Price>70000 orderby pd.ProductID select new{ rt.OrderID,
  2. pd.ProductID,
  3. pd.Name,
  4. pd.UnitPrice,
  5. rt.Quantity,
  6. rt.Price,
  7. }).ToList();

LINQ Pad Query

 

转载于:https://www.cnblogs.com/2zhyi/p/3424786.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, here is an SQL case study for a fictitious e-commerce website called "MyShop": MyShop has the following tables: - Customers: contains customer information such as name, email, phone number, etc. - Orders: contains order information such as order date, customer ID, total price, etc. - Order_Items: contains details of each item in an order such as product ID, quantity, price, etc. - Products: contains product information such as name, description, price, etc. Let's assume we want to answer the following business questions using SQL: 1. What is the total revenue generated by the website in the last month? 2. Who are the top 10 customers in terms of total spending on the website? 3. Which products are the most popular among customers? Here are the SQL queries to answer these questions: 1. What is the total revenue generated by the website in the last month? ```sql SELECT SUM(oi.quantity * p.price) as total_revenue FROM Orders o JOIN Order_Items oi ON o.order_id = oi.order_id JOIN Products p ON oi.product_id = p.product_id WHERE o.order_date >= DATEADD(month, -1, GETDATE()) ``` This query joins the Orders, Order_Items, and Products tables to get the quantity and price of each item in an order and then sums up the revenue for all orders in the last month. 2. Who are the top 10 customers in terms of total spending on the website? ```sql SELECT c.customer_id, c.name, SUM(oi.quantity * p.price) as total_spending FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id JOIN Order_Items oi ON o.order_id = oi.order_id JOIN Products p ON oi.product_id = p.product_id GROUP BY c.customer_id, c.name ORDER BY total_spending DESC LIMIT 10 ``` This query joins the Customers, Orders, Order_Items, and Products tables to get the total spending for each customer and then sorts the result by total spending in descending order and limits the result to the top 10 customers. 3. Which products are the most popular among customers? ```sql SELECT p.product_id, p.name, SUM(oi.quantity) as total_quantity_sold FROM Products p JOIN Order_Items oi ON p.product_id = oi.product_id GROUP BY p.product_id, p.name ORDER BY total_quantity_sold DESC LIMIT 10 ``` This query joins the Products and Order_Items tables to get the total quantity sold for each product and then sorts the result by total quantity sold in descending order and limits the result to the top 10 products.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值