Home  >  Article  >  Database  >  sql多表查询语句与方法

sql多表查询语句与方法

WBOY
WBOYOriginal
2016-06-07 17:46:503282browse

sql多表查询有很多种方法,如有自然连接 INNER JOIN,外边查询LEFT JOIN,交叉查询JOIN,交叉连接JOIN等join on left on 等多的是哦。

sql多表查询语句与方法

sql多表查询有很多种方法,如有自然连接 INNER JOIN,外边查询LEFT JOIN,交叉查询

JOIN,交叉连接JOIN等join on left on 等多的是哦。

下面使用等值连接列出authors和publishers表中位于同一城市的作者和出版社:

  
  Select *
  FROM authors AS a INNER JOIN publishers AS p
  ON a.city=p.city

 

又如使用自然连接,在选择列表中删除authors 和publishers 表中重复列(city和state)

  
  Select a.*,p.pub_id,p.pub_name,p.country
  FROM authors AS a INNER JOIN publishers AS p
  ON a.city=p.city

外边查询

Select a.*,b.* FROM luntan LEFT JOIN usertable as b
  ON a.username=b.username


  
下面使用全外连接将city表中的所有作者以及user表中的所有作者,以及他们所在的城市

  
  Select a.*,b.*
  FROM city as a FULL OUTER JOIN user as b
  ON a.username=b.username

交叉查询

交叉连接不带Where 子句,它返回被连接的两个表所有数据行的笛卡尔积,返回到结果集

合中的数据行数等于第一个表中符合查询条件的数据行数乘以第二个表中符合查询条件的

数据行数。例,titles表中有6类图书,而publishers表中有8家出版社,则下列交叉连接

检索到的记录数将等于6*8=48行。

  
  Select type,pub_name
  FROM titles CROSS JOIN publishers
  ORDER BY type


使用左外连接将论坛内容和作者信息连接起来:

Select a.*,b.* FROM luntan LEFT JOIN usertable as b

ON a.username=b.username

 

下面使用全外连接将city表中的所有作者以及user表中的所有作者,以及他们所在的城市

Select a.*,b.*

FROM city as a FULL OUTER JOIN user as b

ON a.username=b.username


(三)交叉连接

交叉连接不带Where 子句,它返回被连接的两个表所有数据行的笛卡尔积,返回到结果集

合中的数据行数等于第一个表中符合查询条件的数据行数乘以第二个表中符合查询条件的

数据行数。

例,titles表中有6类图书,而publishers表中有8家出版社,则下列交叉连接检索到的记

录数将等

于6*8=48行。

Select type,pub_name

FROM titles CROSS JOIN publishers

orDER BY type 

下面我们来看一个我写的多表查询吧

$sql = "Select zgy_jobs_faces.*,zgy_jobs_index.*,zgy_jobs_option.* from

zgy_jobs_faces,zgy_jobs_index,zgy_jobs_option where   zgy_jobs_option.mulplace

='$city' and zgy_jobs_faces.djobskinds ='$parttime' and zgy_jobs_faces.cid=

zgy_jobs_option.cid and zgy_jobs_option.cid = zgy_jobs_index.cid group by

zgy_jobs_faces.jname order by zgy_jobs_option.jid desc limit 0,30";

用group by 过滤重复的数据

关键词:sql查询,多表查询

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn