SQL内连接用法

时间:2013-12-23 01:03:57

标签: mysql sql sql-server inner-join

我有一个连接许多表的查询,所有这些表都有一个名为businessetityid的列。这个列重复多次。是否有任何简单的方法来处理它。 这是我的疑问:

SELECT * FROM person p 
inner join personemailaddress e on p.BusinessEntityID=e.BusinessEntityID
inner join personpassword ps on p.BusinessEntityID=ps.BusinessEntityID
inner join personphone ph on p.BusinessEntityID=ph.BusinessEntityID
inner join 
( 
select BusinessEntityID from  businessentityaddress b
inner join address a on b.AdressID=a.AdressID
)  ad on ad.BusinessEntityID=p.BusinessEntityID

INTO OUTFILE 'D:\forMongo.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

我想在mongodb.csv文件中只获得一个businessentityid列。

2 个答案:

答案 0 :(得分:2)

是的,请勿使用Select *。而是按照您希望它们在查询中显示的列完全列出列,确保使用正确的列,在它们前面添加表相关名称

例如

SELECT
       e.Town, 
       ph.Mobile 
FROM person p 
inner join personemailaddress e on p.BusinessEntityID=e.BusinessEntityID
inner join personpassword ps on p.BusinessEntityID=ps.BusinessEntityID
inner join personphone ph on p.BusinessEntityID=ph.BusinessEntityID
inner join 
( 
select BusinessEntityID from  businessentityaddress b
inner join address a on b.AdressID=a.AdressID
)  ad on ad.BusinessEntityID=p.BusinessEntityID

INTO OUTFILE 'D:\forMongo.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

答案 1 :(得分:2)

正如JOIN Syntax所述(强调补充):

  

以下列表提供了有关旧版本中当前联接处理与联接处理的几种效果的更多详细信息。术语“先前”表示“在MySQL 5.0.12之前。”

     
      
  • NATURAL联接或USING联接的列可能与之前不同。 具体而言,冗余输出列不再显示SELECT *扩展的列顺序可能与之前不同。
  •   

因此,如果您使用USING而不是ON指定加入条件,则会删除重复的列:

SELECT *
FROM   person             p
  JOIN personemailaddress e  USING (BusinessEntityID)
  JOIN personpassword     ps USING (BusinessEntityID)
  JOIN personphone        ph USING (BusinessEntityID)
  JOIN (
         SELECT BusinessEntityID
         FROM   businessentityaddress b
           JOIN address               a USING (AdressID)
       ) USING (BusinessEntityID)
INTO   OUTFILE 'D:\\forMongo.csv'
FIELDS TERMINATED BY ','
       ENCLOSED   BY '"'
LINES  TERMINATED BY '\n'