MySQL條件查詢


--基本查詢
select
* from 表名 where 判斷條件;

 

模糊查詢

select * from 表名 where name like "張%";   查詢姓張的所有數據

select * from 表名 where name like "張_";    查詢兩個字姓張的    


select * from 表名 where name relike "^張"; relike是用正則表達式查詢 以張開頭的

 

范圍查詢

select * from 表名 where name in ("張三","李四");    查詢姓名為張三和李四的


select * from 表名 where age between 13 and 14;    查詢年齡在13~20歲之間的
select * from 表名 where age not between 13 and 14; 查詢年齡不在13~20歲之間的

select * from 表名 where age is not null; 判斷年齡不能為空

 

 

排序

select * from 表名 where age between 12 and 20 order by;    不帶參數為升序

select * from 表名 where age between 12 and 20 order by dasc; 從大到小

 

聚合函數

count()
select
count(*) asfrom 表名 where 性別="男"; 統計男性有多少人

max,min
select max(身高) as 最高from 表名 where 性別="男"; 統計男最高的身高

select sum(age) as 年齡 from 表名; 統計平均年齡

round()
select round(avg(身高),1) as 平均身高 from 表名; 保留1為小數,多的四舍五入


分組
group by
select count(*) from 表名 group by 性別; 分別統計男女有多少人

select 性別,group_concat(name) from 表名 group by 性別; 查詢每個性別中有哪些人的名字


設置顯示數據條數
limit
select name,數學 from 表名 order by desc 數學 limit 3;
顯示數學最高分的前三名

select * from 表名 limit 0,5; 顯示第一條到第五條
select * from 表名 limit 1,5; 顯示第二條到第六條
 

 

鏈接

liner  內連接
left   ·左連接
right   右連接
select
* from 表1 liner 或 leftright join 表2 on 表1.列 = 表2.列;

select * from 表1 liner 或 left 或 right join 表2 on 表1.列 = 表2.列 having 新表判斷條件;     在新鏈接出來的表用 having 在原表用 where

 

 

創建關聯設置外鍵

alter table 表名1 add foreign key (主鍵字段) references 表名2(副鍵字段)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM