多表查询就是从多张表中去查询数据,在实际开发中大多数情况数据都是存储在多张中的,它们通过一个关联关系连接起来,这样就可以通过这个关联关系去查询到想要的数据。
上面提到了需要通过一个关联关系连接起来,如果不通过关系连接会出现什么情况呢?答案就是笛卡尔积现象。
查询cart表,共计6条数据:
查询goods表,共计9条数据:
若不使用连接关系将这两张表查询,会出现什么情况呢?
我们会发现产生了笛卡尔现象,产生了数据冗余,那么如何才能正确的进行查询呢?这时候我们就用到了多表连接查询。
select cart.*,goods.goods_name,goods.price
from cart,goods
where cart.goods_no = goods.good_no;
我们发现此时查询出了我们期望的6条记录!
因为关联关系是字段是good_no(商品编号),所有可以对应查询到的结果只有6条记录。
接下来我们进行实操!按照上述数据库及表进行下面题目的练习:
select goods.goods_name,account.name
from cart,goods,account
where goods.goods_name='火腿肠' and cart.goods_no=goods.good_no and account.id=cart.account_id;
select account.name
from cart,goods,account,category
where category.name='零食' and cart.goods_no=goods.good_no and account.id=cart.account_id and goods.category_no=category.no;
select account.name,sum(goods.price * cart.num) as total_cost
from cart,goods,account
where account.name='张三' and cart.goods_no=goods.good_no and account.id=cart.account_id;
select account.name ,sum(goods.price * cart.num) AS total_cost
from cart,goods,account
where cart.goods_no=goods.good_no and account.id=cart.account_id group by account.name;
select dayname(cart.create_time) AS weekday_name,sum(goods.price*cart.num) AS total_cost
from cart,goods
where goods.good_no = cart.goods_no
group by dayname(cart.create_time);
select account.name,time(cart.create_time)
from cart,account
where account.name='张三' and account.id = cart.account_id;
select sum(cart.num*(goods.price-goods.cost)) AS total_cost
from cart,goods
where goods.good_no = cart.goods_no;
select goods.goods_name,concat(format((goods.price-goods.cost)/goods.cost*100,2),'%') AS profit
from cart,goods
where goods.good_no = cart.goods_no;
select goods.goods_name
from goods,cart
where goods.good_no=cart.goods_no and cart. create_time between '2023-03-05'and '2023-03-12';
select account.name,(account.money-sum(goods.price * cart.num)) AS balance
from goods,cart,account
where goods.good_no = cart.goods_no and account.id = cart.account_id
group by account.name;
select goods.goods_name,(goods.count-sum(cart.num)) AS inventory
from goods,cart
where goods.good_no = cart.goods_no
group by goods.goods_name;
1.sql中如何对日期进行修改?
--将日期增加一天
update account set create_time=date_add(create_time,interval 1 day);
--将日期增加一月
update account set create_time=date_add(create_time,interval 1 month);
--将日期减少一天
update account set create_time=date_sub(create_time,interval 1 day);
#此函数应用时变量依据需求进行修改,如:year(年)、month(月)、day(日)、hour(时)、minute(分)、second(秒)、microsecond(微秒)
#其中 date_add为增加,date_sub为减少
2.FORMAT格式化
FORMAT(number, decimal_places)
--其中,number 是需要格式化的数值,decimal_places 是需要保留的小数位数。
上面第8题便使用到了FORMAT格式化
在 MySQL 中,CONCAT 函数用于将多个字符串连接在一起。它接受多个字符串作为参数,并按照参数的顺序将它们连接成一个新的字符串。
CONCAT(string1, string2, ...)
其中,string1、string2 等为要连接的字符串参数,可以是常量字符串、列名或其他表达式。CONCAT 函数会将这些参数依次连接起来,形成一个新的字符串,并返回结果