MySQL——查询数据

1.基本查询

SELECT column FROM table;

 

2.有条件查询

SELECT common_name ,scientific_name
FROM birds WHERE family_id =103
LIMIT 3;

 

3.结果排序

-- ORDER BY 默认升序(ASC), 逆序(DESC)

SELECT common_name,scientific_name
FROM birds WHERE family_id =103
ORDER BY common_name
LIMIT 3;

-- ORDER BY 是放在WHERE 之后,LIMIT之前

 

-- IN 匹配多个值

SELECT * FROM bird_families
WHERE scientific_name
IN('Charadriidae','Haematopodidae','Recurviostridae','Scolopacidae');

 

-- <> / !=   (不等于)

SELECT common_name,scientific_name,family_id
FROM birds
WHERE family_id IN (103,160,162,164)
AND common <> ''
ORDER BY common_name
LIMIT 3;

/* 空字符串与NULL: 空字符串不含字符,但属于字符串,不占空间;

NULL表示没有值,占空间 */

 

4.限定结果集

SELECT common_name,scientific_name,family_id
FROM birds
WHERE famiy_id IN (103,160,162,164)
AND common_name <>''
ORDER BY common_name
LIMIT 3,2;

-- LIMIT 连接两个值: 一个是开始位置,一个是行数

 

5.表连接

SELECT common_name AS 'Bird'
bird_families.scientific_name AS 'Family'
FROM birds, bird_families
WHERE birds.family_id = bird_families.family_id
AND order_id = 102
AND common_name <> ''
ORDER BY common_name LIMIT 10;

--  AS 可设置列或表别名,表别名不能加引号。保留字需加引号

 

6.表达式与LIKE

SELECT common_name AS 'Bird'
families.scientific_name AS 'Family',
orders.scientific_name AS 'Order'
FROM birds,bird_families AS families , bird_orders AS orders
WHERE birds.familiy_id= families.familiy_id
AND families.order_id = orders.order_id
AND common_name LIKE 'Least%'
ORDER BY orders.scientific_name,families.scientific_name,common_name
LIMIT 10;

-- ORDER BY 不能使用列的别名,表别名可以。若FROM指定表的别名
-- 则ORDER BY必须用此别名

 

-- REGEXP 正则表达式

SELECT common_name AS 'Birds Great and Small'
FROM birds
WHERE common_name REGEXP 'Great|Least'
ORDER BY family_id LIMIT 10;

SELECT common_name AS 'Birds Great and Small'
FROM birds
WHERE common_name REGEXP 'Great|Least'
AND common_name NOT REGEXP 'Greater'
ORDER BY family_id LIMIT 10;

-- REGEXP 与NOT REGEXP 不区分大小写,若区分大小写,加上BINARY

SELECT common_name AS 'Hawks'
FROM birds
WHERE common_name REGEXP BINARY 'Hawk'
AND common_name NOT REGEXP 'Hawk-Owl'
ORDRE BY family_id LIMIT 10;

 

若表设置了二进制,即设置了latin1_bin 则已经区分大小写,无需加上BINARY

 

MySQL——查询数据

 

 

7.对结果集进行计数和分组

SELECT COUNT(*) FROM birds;

/* COUNT(*)表示统计所有行。若COUNT(column) 表示统计有值的行
即忽略;列中NULL值的行。空或空值(即'')不会被忽略 */

 

SELECT orders.scientific_name AS 'Order',
families.scientific_name AS 'Family',
COUNT(*) AS 'Number of Birds'
FROM birds,bird_families AS families, bird_orders AS orders
WHERE birds.family_id =families.family_id
AND families.order_id = ordes.order_id
AND orders.scientific_name = 'Pelecaniformes'
GROUP BY Family;

 

上一篇:五、HTML5 千纸鹤动画特效


下一篇:CF922E Birds(dp)