MySQL学习(十)

要做:商城的留言板

一般情况,做留言板的显示很容易,直接select查询,再显示出来,但eschop中的留言板难点在于留言数据来自2张表,feedback表和comment表,我们需要把两张表中的内容都取出来,显示。
思路: 从业务逻辑层,用php来解决这个问题
1 先取出feedback表,循环取出数据,放入一个数组
2 再取出comment表,循环取出数据,放入一个数组
3 把取出两个数组合并
4 循环合并后的大数组整理

union关键字,可以给出多条select语句,并将他们的结果组合成单个结果集。合并时,两个表对应的列数和数据类型必须相同。各个select语句之间使用union或union all关键字分隔。union不使用all,执行的时候删除重复的记录,所有返回的行都是唯一的;使用关键字all的作用是不删除重复行也不对结果进行自动排序。

mysql> select s_id,f_name,f_price
    -> from fruits
    -> where f_price < 9.0
    -> union all
    -> select s_id,f_name,f_price
    -> from fruits
    -> where s_id in(101,103);

结果如下

能否从2张表查询在union那?
答:可以,union合并的是”结果集“,不区分来自那张表。

union后的结果集,能否再排序
答:可以

mysql> select goos_id,goods_name,shop_price from goods
    -> where
    -> shop_price < 100
    -> union all
    -> select goos_id,goods_name,shop_price from goods
    -> where
    -> shop_price > 4000
    -> order by shop_price asc;

用union取出第4个栏目的商品和第5个栏目的商品,并按价格升序排列

mysql> select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 4
    -> union all
    -> select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 5
    -> order by shop_price asc;

sql1 union sql2 order by 字段
注意:order by是针对合并后的结果集排的序

使用odrer by的注意事项

mysql> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 4
    -> order by shop_price desc)
    -> union
    -> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 5
    -> order by shop_price desc);

内层的order by语句没用起作用

mysql> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 4
    -> order by shop_price desc)
    -> union
    -> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where
    -> cat_id = 5
    -> order by shop_price desc)
    -> order by shop_price asc;


外层语句还要对最终结果再次排序,因此内层的语句排序就没用意义。因此,内层的order by语句单独使用,,不会影响结果集,仅排序,在执行期间,就被MySQL的代码优化器给优化掉了。内层的order by必须能够影响结果集时才有意义,比如配合limit使用。
问题:查出第3个栏目下,价格前3高的商品和第4个栏目下,价格前2高的商品

mysql> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where cat_id = 4
    -> order by shop_price desc limit 2)
    -> union all
    -> (select goos_id,cat_id,goods_name,shop_price from goods
    -> where cat_id = 3
    -> order by shop_price desc limit 3);

这一次,内层的order by发挥了作用,因为有limit,order by会影响

一道面试题
建立两张表,插入如下数据,

要求结果如下

思路1 左连 union 右连 ,在子查询,如果遇到问题,查if null函数
思路2

mysql> select id,sum(num) from (
    -> select * from a
    -> union all
    -> select * from b) as temp
    -> group by id;

注意 如果不用 union all 结果会不正确

原文地址:https://www.cnblogs.com/Manual-Linux/p/10206874.html