最近做项目再用sql,写一下常用的sql语句。
准备:
创建一个数据库test: SQL------------ CREATE database test;
使用数据库:SQL------------------- use database test;
创建第一张表: SQL---------------CREATE TABLE t_employee ,包含三个字段 emp_id ,name, phone
创建第一张表: SQL---------------CREATE TABLE t_money,包含三个字段 emp_id ,grade, salsry
最简单的SQL: SELECT * FROM tablename; 语法没错,但是实际中却不能用,特别是数据多的时候,用这个句子,小心DBA上门neng死你。
好嘞。查询分两种:单表查询 和 多表查询。
单表查询: SELECT t_employee.emp_id, t_employee.emp_name FROM t_employee WHERE emp_id<10 ORDER BY emp_id DESC
难点是多表查询:
两种写法:
1
SELECT t_employee.emp_id, t_employee.`name`, t_money.salary, t_employee.phone
FROM t_employee, t_money
WHERE t_employee.emp_id = t_money.emp_id
ORDER BY t_employee.emp_id DESC
2
SELECT t_employee.emp_id, t_employee.`name`, t_money.salary, t_employee.phone, <span style="font-family: Arial, Helvetica, sans-serif;">t_employee.grady</span>
FROM t_employee LEFT JOIN t_money
ON t_employee.emp_id = t_money.emp_id
ORDER BY t_money.salary DESC
这里再写一下常用的 AS的用法
as在SQL中两种用法:别名(为结果设置,或者表名) 或者 做is用(这里不介绍)
那么用了as后,上面两个SQL怎么写呢?
1-1
SELECT te.emp_id, te.`name`, tm.salary, te.phone
FROM t_employee AS te, t_money AS tm
WHERE te.emp_id = tm.emp_id
ORDER BY te.emp_id DESC
2-1
SELECT te.emp_id, te.`name`, tm.salary, te.phone,tm.grady
FROM t_employee AS te LEFT JOIN t_money AS tm
ON te.emp_id = tm.emp_id
ORDER BY tm.salary DESC
是不是用了as的别名之后感觉清爽了很多呢,因为在创建表的时候,为了清楚的表示表的意义,所以表名字往往很具体,那么在写sql的时候就比较麻烦(要敲那么长。),所以用as就很好咯。