SQL

题目1:找出那些 没有被 id = 2 的客户 推荐 的客户的姓名。

我一开始写的是

1
2
3
4
5
6
select
`name`
from
Customer
where
referee_id != 2;

但是这样是不对的

因为sql里面的不等于,不包含null

题目2:查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。

这里需要注意的是

Length()和Char_Length()的区别

LENGTH():字节长度,如果有中文,在UTF-8下占用3个字节

CHAR_LENGTH():字符长度

字符 LENGTH() CHAR_LENGTH()
'A' 1 byte 1 character
'你' 3 bytes 1 character
'你好' 6 bytes 2 characters

题目3:获取 Sales 表中所有 sale_id 对应的 product_name 以及该产品的所有 yearprice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
销售表 Sales:

+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) 是销售表 Sales 的主键(具有唯一值的列的组合)。
product_id 是关联到产品表 Product 的外键(reference 列)。
该表的每一行显示 product_id 在某一年的销售情况。
注意: price 表示每单位价格。
产品表 Product:

+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
product_id 是表的主键(具有唯一值的列)。
该表的每一行表示每种产品的产品名称。

两种解法

1
2
3
4
5
6
7
8
9
10
11
12
/* Write your T-SQL query statement below */
--写法一:
select p.product_name, s.year, s.price
from Sales s
inner join Product p
on s.product_id = p.product_id

--写法二:
select p.product_name, s.year, s.price
from Sales s
join Product p
using (product_id)

Using的用法

1.USING 用在 JOIN 中(简化 ON

用于两个表连接时指定 相同名字的列,相当于 ON table1.column = table2.column 的简写

2.USING 用在多表 DELETEUPDATE 中(MySQL 特有)

1
2
3
DELETE t1 FROM table1 t1
JOIN table2 t2 USING (id)
WHERE t2.status = 'inactive';

这表示删除 table1 中满足条件的行。