一、插入数据 (1)INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing'
一、插入数据
(1)INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing')
(2)INSERT INTO Persons (LastName, Address)
VALUES ('Wilson', 'Champs-Elysees'),('Wilson2', 'Champs-Elysees2')
(3)INSERT INTO Persons select * from Persons2
(4)SELECT LastName,FirstName INTO Persons_backup FROM Persons
二、删除数据
(1)DELETE FROM Person WHERE LastName = 'Wilson'
(2)drop Person
三、修改数据
(1)UPDATE Person SET Address = 'Zhongshan 23', City = 'Nanjing'
WHERE LastName = 'Wilson'
(2)update p set p.Address = 'Zhongshan 23'
from Person p inner join City c on p.cityId = c.id where c.name = '北京'
四、查询语句
1、普通查询:
(1)SELECT LastName,FirstName FROM Persons WHERE City='Beijing'
ORDER BY Company DESC, OrderNumber ASC
(2)SELECT DISTINCT Company FROM Orders
(3)SELECT * FROM Persons WHERE (FirstName='Thomas' OR FirstName='William')
AND LastName='Carter'
(4)SELECT * FROM Persons WHERE LastName IN ('Adams','Carter')
(5)SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Adams' AND 'Carter'
(6)SELECT TOP 2 * FROM Persons (只sqlserver)
(7)SELECT * FROM Persons LIMIT 5 (只Mysql)
(8)SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p,
Product_Orders AS po WHERE p.LastName='Adams' AND p.FirstName='John'(别名)
(9)SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2(合并结果集,union all是直接连接,取到得是所有值,
记录可能有重复;union 是取唯一值,记录没有重复)
2、like查询
(1)SELECT * FROM Persons WHERE City LIKE '%' + 'N' + '%'
(2)SELECT * FROM Persons WHERE City LIKE 'N%'(这种方式可能用到索引)
(3)SELECT * FROM user where userName like '发_1_2'(_仅替代一个字符)
(4)SELECT top 10 * FROM user where userId like '[23]%'
([charlist]字符列中的任何单一字符,只sqlserver有用)
(5)SELECT top 10 * FROM user where userId like '[^23]0%'
([^charlist]不在字符列中的任何单一字符,只sqlserver有用)
3、关联查询
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons
INNER JOIN Orders ON Persons.Id_P = Orders.Id_P ORDER BY Persons.LastName
(1)JOIN: 如果表中有至少一个匹配,则返回行
(2)LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
(3)RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
(4)FULL JOIN: 只要其中一个表中存在匹配,就返回行
4、分页查询
(1)SELECT * FROM ceshi limit 0,10(只mysql,从第1个数据开始,取10条数据)
(2)select top 10 o.* from (select row_number() over(order by userId)as rowNumber,* from user) as o where rowNumber>0(只sqlserver,从第1个数据开始,取10条数据)
(3)SELECT * FROM user order by userId OFFSET 0 ROW FETCH NEXT 10 ROWS ONLY
(只sqlserver,新版的sqlserver可用,比上一种高效)
四、java写数据库语句需要特别注意的问题
1、SqlServer 对语句的条数和参数的数量都有限制,分别是 1000 和 2100;
2、Mysql 对语句的长度有限制,默认是 4M;
3、where条件中,=与!=两边都不能有null值,否则判断会出错。需要对有null值的字段作比较时, sqlserver需要用isnull(null,'default_value')把null值转化为默认值再比较;mysql需要用ifnull(null,'default_value')把null值转化为默认值再比较。
--结束END--
本文标题: 常用增删改查sql示例
本文链接: https://lsjlt.com/news/41899.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0