简体   繁体   English

MySQL 加入 - 放置 ON 子句

[英]MySQL Joins - Placement of the ON clause

I recently tried to pull some results and was struggling to work out the correct query to do it.我最近试图提取一些结果,但一直在努力找出正确的查询来完成它。 All the examples I have seen and even my MySQL book show joins as follows:我看过的所有例子连我的MySQL书展都加入如下:

SELECT * 
FROM table_1
LEFT JOIN table_2 LEFT OUTER JOIN table_3 LEFT JOIN table_2
ON table_1.id = table_2.rel_id
AND table_1.id = table_3.rel_id
AND table_3.id = table_2.rel_id
WHERE table_1.some_col = some_vale;

This didn't work and instead, the solution was thus:这没有用,相反,解决方案是:

SELECT *
FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.rel_id
LEFT OUTER JOIN table_3 ON table_1.id = table_3.rel_id
LEFT JOIN table_2 ON table_3.id = table_2.rel_id
WHERE table_1.some_col = some_value;

What is the difference between these two SELECT statements?这两个SELECT语句有什么区别? When should each be used?什么时候应该使用它们? How do怎么做

you determine how the joins work?您确定连接如何工作?

First statement didn`t work because you join table_2 twice with some name and without condition in first time.第一条语句不起作用,因为您第一次使用某个名称且没有条件地加入 table_2 两次。 Left outer join in mysql is fully equivalent left join. mysql 中的 Left outer join 完全等价于 left join。 Eventually first statement fully incorrect.最终第一个陈述完全不正确。

when you join table, you must use "ON" clause or describe join condition in WHERE clause.连接表时,必须使用“ON”子句或在 WHERE 子句中描述连接条件。 If you join one table twice you must add aliases to them like "left join table_2 as t2 left join table_2 as t22".如果您两次连接一个表,则必须为它们添加别名,例如“left join table_2 as t2 left join table_2 as t22”。

Anyway docs will help you:)无论如何文档会帮助你:)

mysql select statement mysql select 声明

You must read MYSQL JOIN Syntax您必须阅读MYSQL JOIN Syntax

Basic Syntax基本语法

     SELECT * FROM first_table ft  
     (LEFT | RIGHT )JOIN second_table st ON st.column = ft.column
     (LEFT | RIGHT )JOIN third_table tt ON tt.column = ft.column (OR st.column)
     WHERE 

Note: Default JOIN is INNER JOIN alternatively you can use below syntax注意:默认JOININNER JOIN或者您可以使用以下语法

SELECT * FROM t1 LEFT JOIN (t2, t3, t4)
                 ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM