MYSQL数据库中常用的表连接有三种:
select 左表别名.字段 from 左表 坐标别名 inner join 右表 右表别名 on 坐标别名.字段 = 右表别名.字段
select * from location a inner join store_info b on a.store_name = b.store_name;
select * from location a, store_info b where a.store_name = b.store_name;
select * from location a inner join store_info b using(store_name);
select * from location a left join store_info b on a.store_name = b.storetore_name;
select * from location a right join store_info b on a.store_name = b.store_name;
对下面的表进行saving比较并且进行排名通过表的自我连接进行实现
表的自我连接达到排名的原理分析及操作思路:
1. 以上面的数据表为例,假设共有四个人,他们手中的金额各不相同。我们已经进行表的自我连接。
2. 使用count计数,只计数大于等于自身手上金额的人数,比如2000的小明,大于等于他的人数只有1个,就计数值也可以当作他的排名
3. 再比如800的小红,大于等于她的有4个人,就该计数值为4,同理可以证明她排名第四。
SELECT A.name, A.saving, count(B.saving) rank FROM paiming A, paiming B WHERE A.saving < B.saving OR (A.saving = B.saving AND A.Name = B.Name) GROUP BY A.name, A.saving ORDER BY rank;
视图:可以被当作是虚拟表或存储查询。
格式:
CREATE VIEW "视图表名" AS "SELECT 语句"; #创建视图表
DROP VIEW "视图表名"; #删除视图表
create view v_region_sales as select a.region region,sum(b.sales) sales from location a inner join store_info b on a.store_name = b.store_name group by region;
查看view表:
注意: 创建view表时如果没有对加入的sql语句的结果进行任何的聚合函数,group by 等修改 ,则可以通过修改view表中的数据,否则不可以进行修改
union联集:将两个SQL语句的结果合并起来,两个SQL语句所产生的字段需要是同样的数据记录种类。
生成结果的数据记录值将没有重复,且按照字段的顺序进行排序。#合并后去重
格式:[select 语句1] UNION [select 语句2];
select store_name from location union select store_name from store_info;
select store_name from location union all select store_name from store_ine_info;
SELECT A.Store_Name FROM location A INNER JOIN Store_Info B ON A.Store_Name = B.Store_Name;
SELECT A.Store_Name FROM location A INNER JOIN Store_Info B USING(Store_Name);
SELECT DISTINCT A.Store_Name FROM location A INNER JOIN Store_Info B USING(Store_Name);
SELECT DISTINCT Store_Name FROM location WHERE (Store_Name) IN (SELECT Store_Name FROM Store_Info);
SELECT DISTINCT A.Store_Name FROM location A LEFT JOIN Store_Info B USING(Store_Name) WHERE B.Store_Name IS NOT NULL;
SELECT A.Store_Name FROM (SELECT B.Store_Name FROM location B INNER JOIN Store_Info C ON B.Store_Name = C.Store_Name) A
GROUP BY A.Store_Name;
SELECT A.Store_Name FROM
(SELECT DISTINCT Store_Name FROM location UNION ALL SELECT DISTINCT Store_Name FROM Store_Info) A
GROUP BY A.Store_Name HAVING COUNT(*) > 1;
SELECT DISTINCT Store_Name FROM location WHERE (Store_Name) IN (SELECT Store_Name FROM store_info);
(1)联级方法中 count(*)<=1
(2)左右内连接 将is not null 改为 is null
(3)子查询 外连接查询 not in (内连接查询)
SELECT CASE ("字段名")
WHEN "条件1" THEN "结果1"
WHEN "条件2" THEN "结果2"
[ELSE "结果N"]
END
FROM "表名";
# "条件"可以是一个数值或是公式。ELSE子句则并不是必须的。
select store_name,case store_name when 'los angeles' then sales * 2 when 'bos,Date from store_info;
1.无值的长度为 0,不占用空间的;而 NULL 值的长度是 NULL,是占用空间的。
2.IS NULL 或者 IS NOT NULL,是用来判断字段是不是为 NULL 或者不是 NULL,不能查出是不是无值的。
3.无值的判断使用='‘或者<>’'来处理。<> 代表不等于。
4.在通过 count()指定字段统计有多少行数时,如果遇到 NULL 值会自动忽略掉,遇到无值会加入到记录中进行计算。
select "字段" from "表名" where "字段" regexp '正则表达式';