15个初学者必看的基础SQL查询语句
前端之家收集整理的这篇文章主要介绍了
15个初学者必看的基础SQL查询语句,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
本文将分享15个初学者必看的基础SQL查询语句,都很基础,但是你不一定都会,所以好好看看吧。
1、创建表和数据插入sql
我们在开始创建数据表和向表中插入演示数据之前,我想给大家解释一下实时数据表的设计理念,这样也许能帮助大家能更好的理解SQL查询。
在数据库设计中,有一条非常重要的规则就是要正确建立主键和外键的关系。
现在我们来创建几个餐厅订单管理的数据表,一共用到3张数据表,Item Master表、Order Master表和Order Detail表。
创建表:
创建Item Master表:
sql;">
CREATE TABLE [dbo].[ItemMasters](
[Item_Code] [varchar](20) NOT NULL,[Item_Name] [varchar](100) NOT NULL,[Price] Int NOT NULL,[TAX1] Int NOT NULL,[Discount] Int NOT NULL,[Description] [varchar](200) NOT NULL,[IN_DATE] [datetime] NOT NULL,[IN_USR_ID] [varchar](20) NOT NULL,[UP_DATE] [datetime] NOT NULL,[UP_USR_ID] [varchar](20) NOT NULL,CONSTRAINT [PK_ItemMasters] PRIMARY KEY CLUSTERED
(
[Item_Code] ASC
)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
向Item Master表插入数据:
<div class="jb51code">
<pre class="brush:sql;">
INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
VALUES
('Item001','Coke',55,1,'Coke which need to be cold',GETDATE(),'SHANU','SHANU')
INSERT INTO [ItemMasters] ([Item_Code],[UP_USR_ID])
VALUES
('Item002','Coffee',40,2,'Coffe Might be Hot or Cold user choice',[UP_USR_ID])
VALUES
('Item003','Chiken Burger',125,5,'Spicy',[UP_USR_ID])
VALUES
('Item004','Potato Fry',15,'No Comments','SHANU')
创建Order Master表:
sql;">
CREATE TABLE [dbo].[OrderMasters](
[Order_No] [varchar](20) NOT NULL,[Table_ID] [varchar](20) NOT NULL,CONSTRAINT [PK_OrderMasters] PRIMARY KEY CLUSTERED
(
[Order_No] ASC
)WITH (PAD_INDEX = OFF,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
向Order Master表插入数据:
sql;">
INSERT INTO [OrderMasters]
([Order_No],[Table_ID],[UP_USR_ID])
VALUES
('Ord_001','T1','','SHANU')
INSERT INTO [OrderMasters]
([Order_No],[UP_USR_ID])
VALUES
('Ord_002','T2','Mak','MAK')
INSERT INTO [OrderMasters]
([Order_No],[UP_USR_ID])
VALUES
('Ord_003','T3','RAJ','RAJ')
创建Order Detail表:
<div class="jb51code">
<pre class="brush:sql;">
CREATE TABLE [dbo].[OrderDetails](
[Order_Detail_No] varchar NOT NULL,[Order_No] varchar CONSTRAINT fk_OrderMasters FOREIGN KEY REFERENCES OrderMasters(Order_No),[Item_Code] varchar CONSTRAINT fk_ItemMasters FOREIGN KEY REFERENCES ItemMasters(Item_Code),[Notes] varchar NOT NULL,[QTY] INT NOT NULL,CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED
(
[Order_Detail_No] ASC
)WITH (PAD_INDEX = OFF,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--Now let’s insert the 3 items for the above Order No 'Ord_001'.
INSERT INTO [OrderDetails]
([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY],[UP_USR_ID])
VALUES
('OR_Dt_001','Ord_001','Item001','Need very Cold',3,'SHANU')
INSERT INTO [OrderDetails]
([Order_Detail_No],[UP_USR_ID])
VALUES
('OR_Dt_002','Item004','very Hot ',[UP_USR_ID])
VALUES
('OR_Dt_003','Item003','Very Spicy',4,'SHANU')
向Order Detail表插入数据:
sql;">
INSERT INTO [OrderDetails]
([Order_Detail_No],[UP_USR_ID])
VALUES
('OR_Dt_004','Ord_002','Item002','Need very Hot',[UP_USR_ID])
VALUES
('OR_Dt_005',[UP_USR_ID])
VALUES
('OR_Dt_006','Ord_003','SHANU')
2、简单的Select查询语句
Select查询语句是sql中最基本也是最重要的DML语句之一。那么什么是DML?DML全称Data Manipulation Language(数据操纵语言命令),它可以使用户能够查询数据库以及操作已有数据库中的数据。
下面我们在sql Server中用select语句来查询我的姓名(Name):
sql;">
SELECT 'My Name Is SYED SHANU'
-- With Column Name using 'AS'
SELECT 'My Name Is SYED SHANU' as 'MY NAME'
-- With more then the one Column
SELECT 'My Name' as 'Column1','Is' as 'Column2','SYED SHANU' as 'Column3'
在数据表中使用select查询:
sql;">
-- To Display all the columns from the table we use * operator in select Statement.
Select * from ItemMasters
-- If we need to select only few fields from a table we can use the Column Name in Select Statement.
Select Item_Code,Item_name as Item,Price,Description,In_DATE
FROM
ItemMasters
3、合计和标量函数
合计函数和标量函数都是sql Server的内置函数,我们可以在select查询语句中使用它们,比如Count(),Max(),Sum(),Upper(),lower(),Round()等等。下面我们用sql代码来解释这些函数的用法:
returns the Total no of records from table,AVG() returns the Average Value from Colum,MAX() Returns MaX Value from Column
--,MIN() returns Min Value from Column,SUM() sum of total from Column
Select Count(*) TotalRows,AVG(Price) AVGPrice,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) PriceTotal
FROM ItemMasters
-- Scalar
-- UCASE() -> Convert to Upper Case,LCASE() -> Convert to Lower Case,-- SUBSTRING() ->Display selected char from column ->SUBSTRING(ColumnName,StartIndex,LenthofChartoDisplay)
--,LEN() -> lenth of column date,-- ROUND() -> Which will round the value
SELECT UPPER(Item_NAME) Uppers,LOWER(Item_NAME) Lowers,SUBSTRING(Item_NAME,3) MidValue,LEN(Item_NAME) Lenths,LEN(Item_NAME)) MidValuewithLenFunction,ROUND(Price,0) as Rounded
FROM ItemMasters
在我们的项目数据表中基本都会使用到日期列,因此日期函数在项目中扮演着非常重要的角色。有时候我们对日期函数要非常的小心,它随时可以给你带来巨大的麻烦。在项目中,我们要选择合适的日期函数和日期格式,下面是一些sql日期函数的例子:
to Display the Current Date and Time
-- Format() -> used to display our date in our requested format
Select GETDATE() CurrentDateTime,FORMAT(GETDATE(),'yyyy-MM-dd') AS DateFormats,'HH-mm-ss')TimeFormats,CONVERT(VARCHAR(10),10) Converts1,CONVERT(VARCHAR(24),113),CONVERT(NVARCHAR,getdate(),106) Converts2,-- here we used Convert Function
REPLACE(convert(NVARCHAR,106),' ','/') Formats-- Here we used replace and --convert functions.
--first we convert the date to nvarchar and then we replace the '' with '/'
select * from Itemmasters
Select ITEM_NAME,IN_DATE CurrentDateTime,FORMAT(IN_DATE,IN_DATE,convert(NVARCHAR,'/') Formats
FROM Itemmasters
DatePart –> 该函数可以获取年、月、日的信息。
DateADD –> 该函数可以对当前的日期进行加减。
DateDiff –> 该函数可以比较2个日期。
<div class="jb51code">
<pre class="brush:sql;">
--Datepart DATEPART(dateparttype,yourDate)
SELECT DATEPART(yyyy,getdate()) AS YEARs,DATEPART(mm,getdate()) AS MONTHS,DATEPART(dd,getdate()) AS Days,DATEPART(week,getdate()) AS weeks,DATEPART(hour,getdate()) AS hours
--Days Add to add or subdtract date from a selected date.
SELECT GetDate()CurrentDate,DATEADD(day,12,getdate()) AS AddDays,-4,getdate()) AS FourDaysBeforeDate
-- DATEDIFF() -> to display the Days between 2 dates
select DATEDIFF(year,'2003-08-05',getdate()) yearDifferance,DATEDIFF(day,-24,getdate()),getdate()) daysDifferent,DATEDIFF(month,DATEADD(Month,6,getdate())) MonthDifferance
First Display top 2 Records
Select TOP 2 Item_Code,In_DATE
FROM ItemMasters
--> to Display the Last to Records we need to use the Order By Clause
-- order By to display Records in assending or desending order by the columns
Select TOP 2 Item_Code,In_DATE
FROM ItemMasters
ORDER BY Item_Code DESC