📜  left join cockroachdb (1)

📅  最后修改于: 2023-12-03 15:02:40.145000             🧑  作者: Mango

Left Join in CockroachDB

In CockroachDB, LEFT JOIN combines the rows of two tables based on a common column, and returns all the rows from the left table along with matching rows from the right table. If there are no matching rows in the right table, then NULL values are displayed for the right table's columns.

The syntax for LEFT JOIN in CockroachDB is as follows:

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

Let's assume we have two tables - employees and departments.

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  department_id INT
);

CREATE TABLE departments (
  id INT PRIMARY KEY,
  name VARCHAR(255)
);

INSERT INTO employees (id, name, department_id)
VALUES (1, 'John', 1),
       (2, 'Jane', 1),
       (3, 'Bob', 2),
       (4, 'Alice', NULL);

INSERT INTO departments (id, name)
VALUES (1, 'Sales'),
       (2, 'Marketing');

Now, suppose we want to retrieve all the employee names along with their department names. We can achieve this using a LEFT JOIN as shown below:

SELECT e.name, d.name as department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.id;

The output of this query will be as follows:

| name | department_name | |----------|----------------| | John | Sales | | Jane | Sales | | Bob | Marketing | | Alice | NULL |

In this output, you can see that all the employee names are displayed, and the department names are also displayed for the employees who belong to a department. For the employee 'Alice', who doesn't belong to any department, the department name is displayed as NULL.

Conclusion

LEFT JOIN is a useful feature in CockroachDB that allows you to combine data from two or more tables in a meaningful way. By using LEFT JOIN, you can retrieve all the data from one table and match it with data from another table, even if there are no matching rows in the other table. This is a powerful way to extract insights and analyze data from multiple sources.