以某字符或某字符串开头,而且不以某某字符串开头
select * from products where name regexp '^str1|^str2' and
CompanyName not regexp '^str3|^str4'
上面为以str1或str2开头,且不以str3和str4开头,regexp中的’|‘在肯定时’或’,否定时是‘且’
select中二次调用变量实现循环累加
1st
select @x:=@x+1 rowno,a.* from products a join (select @x:=0) b
添加一个行号,比row_number()over()更快
join (select @x:=0) 可理解为每行的rowno列初始为0然后在一行行执行过程中累加
2nd
set @x=' ';
select @x:=contact(@x,'/',CustomerName) from customers where region='浙江省';
对浙江省客户名称连接显示在一行
循环加连接利用union 还可处理出第一行第一列全是name,第二行是Adress的效果
Mysql从给定的一个数组中随机取一个数
select convert(elt(floor(10*rand())+1,'11','13','17','19','21','23','29','31','37','41'),decimal(8,2));
实现从10个数中随机取出一个数。
join 某单值来定义初值或是定值
该定值为某随机值,如下
select ID,name from products
join(select @x:=(select categoryid from categories order by rand() limit 1)) a
where categoryid=@x;
下面的却不行
select categoryid,productname from products
join(select @x:=categoryid from categories order by rand() limit 1) a
where categoryid=@x;
MySQl多个左右连接left join ,right join,join
select *from customers left join employees using(id) left join students using(num);
select *from students join employees using(id) right join customers using(num);
上面两条语句等价
若只要一个表的全部行显示,可以将其写在最后再用一个right join就好了
left join与right join组合是没有意义的,因为最终只能一个表全部行显示,left join 与right join也是能相互转换的
距现在多少年用year(now())-year(orderdate)
一般不能year(now()-orderdate),因为now()返回的时间精确到秒,日期格式一致才能相减
with as里不能给变量赋值
with tmp as(select @x:=id from products where Xname='哈喽' limit 1)
selects *from students where id=@x;
上面是错的,改成into也一样还是不行
关于别名
with as里的表达式要取别名
衍生表要取别名
一般复杂表达式都取别名
with as里中的select语句不能出现重复相同的列而一般select中可出现重复相同的列