指定查询列和列
查询表中所有字段

  1. SELECT * FROM MAIL;

按照字段过滤

  1. SELECT srcuser,srchost,t,size FROM mail;

按照关键字匹配模式查询

  1. SELECT t,srcuser,srchost FROM mail WHERE srchost = 'venus';
  2. SELECT t,srcuser,srchost FROM mail WHERE srchost LIKE 's%';

where查询多个条件,不同条件可以检查不同的列.

  1. SELECT * FROM mail WHERE srcuser = 'barb' AND dstuser = 'tricia';

通过CONCAT()将srcuser和srchost列结合在一起

  1. SELECT t,CONCAT(srcuser,'@',srchost),size FROM mail;
    指定查询结果列别名
    通过表达式重新格式化t列中的日期,再使用另一个表达式连接srcuser和srchost而生成
  2. SELECT DATE_FORMAT(t,'%M,%e,%Y'), CONCAT(srcuser,'@',srchost),size FROM mail;

指定输出列的名称,使用AS 别名

  1. SELECT DATE_FORMAT(t,'%M,%e,%Y') as date_sent,CONCAT(srcuser,'@',srchost) AS sender,size FROM mail;
  2. SELECT DATE_FORMAT(t,'%M,%e,%Y') AS 'Date of message',CONCAT(srcuser,'@',srchost) AS 'Message sender',size AS 'Number of bytes' FROM mail;
  3. SELECT t,srcuser,dstuser,size/1024 AS kilobytes FROM mail WHERE size/1024 > 500;

查询结果排序
一列或多列进行排序

  1. SELECT * FROM mail WHERE dstuser = 'tricia' ORDER BY srchost,srcuser;
  2. SELECT * FROM mail WHERE size > 50000 ORDER BY size DESC;

过滤重复行
生成一组具有唯一查询结果.

  1. SELECT DISTINCT srcuser FROM mail;
  2. SELECT COUNT(DISTINCT srcuser) FROM mail;
  3. SELECT DISTINCT YEAR(t),MONTH(t),DAYOFMONTH(t) FROM mail;

处理NULL值
查询NULL值和非空值

  1. select * FROM expt WHERE score IS NULL;
  2. SELECT * FROM expt WHERE score IS NOT NULL;

使用IF()将NULL映射成字符串Unknow

  1. SELECT subject,test,IF(score IS NULL,'Unknown',score) AS 'score' FROM expt;

视图简化查询
计算表达式来定义视图

  1. SELECT DATE_FORMAT(t,'%M,%e,%Y') AS date_sent,CONCAT(srcuser,'@',srchost) AS sender,concat(dstuser,'@',dsthost) AS recipient,size FROM mail;
  2. CREATE VIEW mail_view AS SELECT DATE_FORMAT(t,'%M,%e,%Y') AS date_sent,CONCAT(srcuser,'@',srchost) AS sender,CONCAT(dstuser,'@',dsthost) AS recipient,size FROM mail;
  3. SELECT date_sent,sender,size FROM mail mail_view WHERE size > 1000000 ORDER BY size;

多表查询
比较profile表中id列与profile_contact表中profile_id列,将值相同行连接起来

  1. SELECT id,name,service,contact_name FROM profile INNER JOIN profile_contact ON id=profile_id;
  2. SELECT * FROM profile_contact WHERE profile_id = (SELECT id FROM profile WHERE name = 'Nancy');

LIMIT子句进行查询多少行数据

  1. SELECT * FROM profile LIMIT 1;
  2. SELECT * FROM profile LIMIT 3;
  3. SELECT * FROM profile ORDER BY birth LIMIT 1;
  4. SELECT * FROM profile ORDER BY birth DESC LIMIT 1;
  5. SELECT name,DATE_FORMAT(birth,'%m-%d') AS birthday FROM profile ORDER BY birthday LIMIT 1;
  6. SELECT * FROM profile ORDER BY birth LIMIT 2,1;
  7. SELECT * FROM profile ORDER BY birth DESC LIMIT 2,1;
  8. SELECT COUNT(*) FROM profile;

返回最后4行

  1. SELECT name,birth FROM profile ORDER BY birth DESC LIMIT 4;
  2. SELECT * FROM (SELECT name,birth FROM profile ORDER BY birth DESC LIMIT 4) AS T ORDER BY birth;