MySQL中的Left Join用于查询多个表中的记录。该子句类似于可以在FROM关键字之后立即与SELECT语句一起使用的内部联接子句。当无涯教程使用Left Join子句时,它将返回第一个(左侧)表中的所有记录,甚至没有从第二个(右侧)表中找到匹配的记录。如果找不到右侧表中的任何匹配记录,则返回null。
可以通过以下可视化表示来理解它,其中"Left Join"返回左侧表中的所有记录,而仅返回右侧表中的匹配记录:
以下语法说明了Left Join子句以连接两个或多个表:
SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON Join_Condition;
在以上语法中, table1 是左侧表,而 table2 是右侧表。此子句根据指定的连接条件(Join_Condition)返回表1中的所有记录和表2中的匹配记录。
让无涯教程举一些例子来了解Left Join或Left Outer Join子句的工作方式:
在这里,将创建两个表" customers" 和" orders" ,其中包含以下数据:
表:customers
表:orders
要从两个表中选择记录,请执行以下查询:
SELECT customers.customer_id, cust_name, price, date FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;
成功执行查询后,它将给出以下输出:
表客customers和orders具有相同的列名,即customer_id。在这种情况下,MySQL Left Join也可以与USING子句一起使用来访问记录。以下语句使用带有USING关键字的Left Join子句返回客户ID(customer_id),客户名称(cust_name),职业(occupation),价格(price)和日期(date)。
SELECT customer_id, cust_name, occupation, price, date FROM customers LEFT JOIN orders USING(customer_id);
上面的语句将给出以下输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/mysql/mysql-left-join.html
来源:LearnFk无涯教程网
Left Join也可以与GROUP BY子句一起使用。下面的语句使用Left Join子句和GROUP BY子句返回客户ID(customer_id),客户名(cust_name),资格(qualification),价格(price)和日期(date)。
SELECT customers.customer_id, cust_name, qualification, price, date FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id GROUP BY price;
上面的语句将给出以下输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/mysql/mysql-left-join.html
来源:LearnFk无涯教程网
WHERE子句用于从表中返回过滤器结果。下面的示例使用Left Join子句对此进行说明:
SELECT customer_id, cust_name, occupation, price, date FROM customers LEFT JOIN orders USING(customer_id) WHERE price>2500;
该语句给出以下结果:
无涯教程已经创建了两个名为" customers" 和" orders" 的表。再创建一个表,并将其命名为" contacts",其中包含以下数据:
执行以下语句以加入三个表的客户,订单和联系人:
SELECT customers.customer_id, cust_name, order_id, price, cellphone FROM customers LEFT JOIN contacts ON customer_id = contact_id LEFT JOIN orders ON customers.customer_id = orders.customer_id ORDER BY income;
成功执行以上查询后,将给出以下输出:
在Left Join中,条件WHERE和ON给出不同的结果。无涯教程可以查看以下查询以了解它们之间的差异:
WHERE子句
SELECT cust_name, occupation, order_id, price, date FROM customers LEFT JOIN orders USING(customer_id) WHERE price=2500;
它将返回以下输出:
ON 子句
SELECT cust_name, occupation, order_id, price, date FROM customers LEFT JOIN orders ON price=2500;
它将给出以下输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)