📜  ms sql left join select - SQL (1)

📅  最后修改于: 2023-12-03 14:44:24.955000             🧑  作者: Mango

MS SQL Left Join Select

The LEFT JOIN operation in MS SQL is used to retrieve records from multiple tables based on a related column value. It returns all the rows from the left table and the matching rows from the right table. If there is no match, NULL values are returned for the right table columns.

Syntax:
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Example:

Consider the following two tables, employees and departments, with a common column dept_id:

employees table:

| emp_id | emp_name | dept_id | |--------|-----------|---------| | 1 | John | 1 | | 2 | Lisa | 2 | | 3 | Michael | 1 | | 4 | Sarah | 3 | | 5 | David | NULL |

departments table:

| dept_id | dept_name | |---------|--------------| | 1 | IT | | 2 | Sales | | 3 | Marketing | | 4 | Finance |

To retrieve all employees and their corresponding department names, you can use the following SQL query:

SELECT employees.emp_name, departments.dept_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;

This will produce the following result:

| emp_name | dept_name | |----------|-----------| | John | IT | | Lisa | Sales | | Michael | IT | | Sarah | Marketing | | David | NULL |

The LEFT JOIN ensures that all rows from the left table (employees) are returned, even if there is no matching record in the right table (departments). In this case, David's department is not specified (NULL in dept_id), so it appears as NULL in the result.

Note: Markdown does not support rendering of actual table results, so the above result table is shown as a formatted table. In your code snippet, you should replace the formatted table with a plain code block to represent the query output.