SELECT * FROM student WHERE s_sex='男' | |
ON组合 | SELECT * FROM student LEFT JOIN score on student.s_id=score.s_id; |
ON 语法 | SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name; 说明: - ON 语句用于 指定两个表格之间的连接条件,它通常用于组合各种数据。 - INNER JOIN 是一个关键字,用来指定表格之间的联接方式。 例如: SELECT users.user_id, orders.order_id FROM users INNER JOIN orders ON users.user_id = orders.user_id; 这个查询将返回两个表中具有相同 user_id 的行。 |
ON & Where 组合 | SELECT * FROM student LEFT JOIN score on student.s_id=score.s_id WHERE s_name='李强' |
IN组合 | SELECT * FROM score WHERE s_id in (SELECT s_id FROM student WHERE s_name='李强') |
IN 语法 | SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...); 说明: - IN 操作符用于 在一组数据中指定要搜索的内容。 - IN 操作符常常和 WHERE 语句一起使用。当指定的值与表格中的一行数据的指定列匹配时,该行数据就会被返回。 例如: SELECT * FROM customers WHERE city IN ('Paris','London'); 这个查询将返回两座城市的所有客户的记录。 |
AS组合 | select * from score as a LEFT JOIN student as b on a.s_id=b.s_id where s_name='李强' |
left join数据筛选问题 | on后面的条件只能对left join右边的表进行筛选,左表匹配不到右表数据会在原右表位置处显示null,left join左边的表数据不受约束,将on后的条件加到where后会对所有数据进行筛选。 |
左连接 | 以左表为基础,显示左表中的所有值,不论是否与关联条件相匹配,而右表中的数据只显示与关联条件相匹配的列,不匹配的列无需用null值填充。 select 字段名 from 表A left(outer) join 表B on 表A.字段名1 = 表B.字段名2; |
右连接 | 以右表为基础,根据on后面给出的条件将两表连接起来,结果会将右表所有的查询信息列出,右连接又称为右外连接属于外连接的一种。需显示右表的所有值,与左表条件不符的值可用null值代替。 select 字段名 from 表A right(outer) join 表B on 表A.字段名1 = 表B.字段名2; |
内连接 | 使用比较运算符根据每个表共有的列的值匹配两个表中的行,只连接两个表条件相符的行。 select 字段名 from 表A inner join 表B on 表A.字段名1 = 表B.字段名2; |
全连接 | 完整外部连接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。 select 字段名 from 表A union join 表B on 表A.字段名1 = 表B.字段名2; |
相同数据重复筛选使用问题 | with <name> as() mysql内可以使用with as生成临时表,<name>为临时表的名字,使用如下: with arc as( select id,arc.title,update_time,is_top,cId,pid,name_id from article arc where is_del = 0 ) select * from arc |
根据某个字段排序取每个类别最后三条数据或前三条数据 | select * from ( select cId,title,content( select count(*)+1 from arc a1 where (a1.cId = a2.cId) and a1.updateTime > a2.updateTime )updateTimeSort from arc a2 ) a3 |
查找另一表内和本表相关字段的数量 | select art.title,art.content, count(case afl.fav when 1 then 1 end) as collectNum, count(case afl.like when 1 then 1 end) as likeNum from article art left join article_favor_like afl on afl.arc_id = art.id group by afl.arc_id //这是关键 |
union的使用 | select id,title,content,1 isArc from arc union select id,name,content,0 isArc from news |
limit的巧用 | limit一般用于分页,功能是获取指定区间内的数据 select * from arc where id = 12 limit 1 |
update ignore和insert ignore的使用 | //标题是唯一索引,'新标题'存在则更新操作不执行 update ignore arc set title = '新标题' //标题是唯一索引,'标题1号'存在则插入操作不执行 insert ignore into arc values(null,'标题1号','文章内容') |
mysql存在更新,不存在则插入 | 当插入的数据存在时更新数据,不再是不做任何操作,例子: //本例子中title不是唯一索引,id是主键 insert into arc values(1,'标题1号','文章内容') on duplicate key update title='标题1号' //若要更新多个字段使用’,'隔开,例:title='标题1号',content='文章内容' |
sql语句
于 2023-08-18 17:30:21 首次发布