MySQL关联语句用于在查询中连接两个或多个表,以从这些表中获取相关数据,关联语句可以分为内连接、左连接、右连接和全连接。
1、内连接(INNER JOIN)
内连接是最常用的关联类型,它会返回两个表中具有匹配行的结果,只有当两个表中的记录有匹配的值时,才会返回结果。
语法:
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
示例:
SELECT customers.customer_name, orders.order_date FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id;
2、左连接(LEFT JOIN)
左连接会返回左表的所有记录,即使右表中没有匹配的记录,如果右表中没有匹配的记录,则结果集中的右表列将显示为NULL。
语法:
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
示例:
SELECT customers.customer_name, orders.order_date FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;
3、右连接(RIGHT JOIN)
右连接会返回右表的所有记录,即使左表中没有匹配的记录,如果左表中没有匹配的记录,则结果集中的左表列将显示为NULL。
语法:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
示例:
SELECT customers.customer_name, orders.order_date FROM customers RIGHT JOIN orders ON customers.customer_id = orders.customer_id;
4、全连接(FULL JOIN)
全连接会返回左表和右表中所有匹配的行,如果没有匹配的行,则结果集将为NULL,全连接在MySQL中不支持,但可以通过组合左连接和右连接来实现。
示例:
SELECT customers.customer_name, orders.order_date, COALESCE(orders.order_date, 'No Order') AS order_status FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id; UNION ALL SELECT customers.customer_name, NULL AS order_date, 'No Order' AS order_status FROM customers WHERE customer_id NOT IN (SELECT DISTINCT customer_id FROM orders);
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/639308.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复