【398天】我愛刷題系列157(2018.03.10)

@(躍遷之路)專欄數據庫

叨叨兩句

  1. ~

SQL習題052——MySQL多表查詢基礎鞏固

--新建一個day09_exercise的數據庫code

create database day09_exercise;
use day09_exercise;

-- 用戶表(user)
create table user (ci

`id` int auto_increment primary key,                
      `username` varchar(50)  -- 用戶姓名                                                
    );

-- 訂單表(orders)
create table orders (rem

`id` int  auto_increment primary key,                                  
      `price` double,                                           
      `user_id` int                                       
    );

-- 給訂單表添加外鍵約束
alter table orders add constraint user_fk foreign key (user_id) references user(id); table

-- 向user表中添加數據基礎

insert into user values(3,'張三');
    insert into user values(4,'李四');
    insert into user values(5,'王五');
    insert into user values(6,'趙六');

-- 向orders 表中插入數據select

insert into orders values(1,1314,3);
    insert into orders values(2,1314,3);
    insert into orders values(3,15,4);
    insert into orders values(4,315,5);
    insert into orders values(5,1014,null);

練習:
--查詢用戶的訂單,沒有訂單的用戶不顯示im

select *from user,orders where user.id=orders.user_id;
或者select * from user join orders on user.id=orders.user_id;

--查詢全部用戶的訂單詳情專欄

select *from user left join orders on user.id=orders.user_id;

--查詢全部訂單的用戶詳情數據

select *from user right join orders on user.id=orders.user_id;

練習:
--查看用戶爲張三的訂單詳情

思路:查看用戶爲張三的訂單詳情
    select id from user where username = "張三";
    select * from orders where user_id = ?
        
合二爲一:
答案:select * from orders where user_id = (select id from user where username = "張三");

--查詢出訂單的價格大於300的全部用戶信息。

思路:select user_id from orders where price>300;-- 3 3 5 null
select * from user where id in ();
            
合二爲一:
答案:select * from user where id in (select user_id from orders where price>300);

--查詢訂單價格大於300的訂單信息及相關用戶的信息。

SELECT *FROM USER,orders WHERE user.id=orders.user_id AND orders.price > 300;
相關文章
相關標籤/搜索