📅  最后修改于: 2023-12-03 14:47:40.371000             🧑  作者: Mango
在SQL中,JOIN、IN和EXISTS都是用来查询多个表的数据的关键字,但它们的用法和作用却有所不同。
JOIN是用来连接两个或多个表,以获取其中的共同数据的关键字。JOIN的类型有INNER JOIN、LEFT JOIN、RIGHT JOIN和FULL OUTER JOIN。
-- INNER JOIN
SELECT *
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
-- LEFT JOIN
SELECT *
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
-- RIGHT JOIN
SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
-- FULL OUTER JOIN
SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
IN是用来筛选匹配给定值中的任意一个值的关键字。IN可以在SELECT、UPDATE、DELETE语句中使用。
SELECT *
FROM table1
WHERE column IN (value1, value2, ...);
UPDATE table
SET column = value
WHERE column IN (value1, value2, ...);
DELETE FROM table
WHERE column IN (value1, value2, ...);
EXISTS是用来检查关联表中是否有符合条件的记录的关键字。如果存在符合条件的记录则返回TRUE,否则返回FALSE。EXISTS可以在SELECT、UPDATE、DELETE语句中使用。
SELECT *
FROM table1
WHERE EXISTS (SELECT *
FROM table2
WHERE table1.column = table2.column);
UPDATE table1
SET column = value
WHERE EXISTS (SELECT *
FROM table2
WHERE table1.column = table2.column);
DELETE FROM table1
WHERE EXISTS (SELECT *
FROM table2
WHERE table1.column = table2.column);