MySQL子查詢,聯結表

2021-10-17 14:37:24 字數 1903 閱讀 2126

子查詢:

select cust_id from orders where order_num in (select order_num from orderitems where prod_id = 'tnt2');對每個客戶執行count()計算,應該將count()作為乙個子查詢:select cust_name, cust_state, (select count(*) from orders where orders.cust_id = customers.cust_id) as orders from customers order by cust_name;

聯結表:

select vend_name, prod_name, prod_price from vendors, products where vendors.vend_id = products.vend_id order by vend_name, prod_name;如果沒有where將輸出笛卡爾積(cartesian product),即沒有聯結條件的表關係返回的結果為笛卡兒積,簡單的說就是每個**商匹配每個產品,它包括了**商不正確的產品。

內部聯結:select vend_name, prod_name, prod_price from vendors inner join products on vendors.vend_id = products.vend_id;聯結多個表:select prod_name, vend_name, prod_price, quantity from orderitems, products, vendors where products.vend_id = vendors.vend_id and orderitems.prod_id = products.prod_id and order_num =20005;使用表別名:select cust_name, cust_contact from customers as c, orders as o, orderitems as oi where c.cust_id = o.cust_id and oi.order_num = o.order_num and prod_id = 'tnt2';自聯結:select prod_id, prod_name from products where vend_id = (select vend_id from products where prod_id = 'dtntr');這是一種子查詢的方式,也可以用自聯結代替:select p1.prod_id, p1.prod_name from products as p1, products as p2 where p1.vend_id = p2.vend_id and p2.prod_id = 'dtntr';外部聯結:select customers.cust_id, orders.order_num from customers left outer join orders on customers.cust_id = orders.cust_id;(在使用outer join語法時,必須使用right或left關鍵字 指定包括其所有行的表(right指出的是outer join右邊的表,而left指出的是outer join左邊的表)。上面的例子使用left outer join從from子句的左邊表(customers表)中選擇所有行。)

要檢索所有客戶及每個客戶所下的訂單數:select customers.cust_name, customers.cust_id, count(orders.order_num) as num_ord from customers inner join orders on customers.cust_id = orders.cust_id group by customers.cust_id;

子查詢 聯結表 建立高階聯結 組合查詢

巢狀在其他查詢中的查詢 利用子查詢過濾select cust id from orders where order num in select order num from orderitems where prod id tnt2 作為計算字段使用子查詢select cust name,cust ...

MySQL聯結查詢和子查詢

2018 2 24 16 18 12 星期六 今天需要統計乙個運營活動的資料,涉及三個表,分組比較多 活動描述 每個人可以領取多張卡片,好友也可以贈送其卡片,20或40張卡片可以兌換乙個獎品 要求統計出 1.每個使用者的個人資訊,2.領取的卡總數,3.自己領的卡的數目,4.好友送的卡的數目,5.兌換...

SQL使用子查詢 聯結表 建立高階聯結

利用子查詢進行過濾select cust name,cust contact from customers where cust id in select cust id from orders where order num in select order num from orderitems ...