合并两个选择查询

时间:2011-09-29 09:14:44

标签: mysql sql

我想将这两个Select查询合并为单个查询。我怎么能这样做?

 SELECT link_id, COUNT(*)  FROM Loc  GROUP BY link_id 

     SELECT Slink.[xlink:Show],Loc.[xlink:show],
     Slink.[xlink:actuate],Loc.[xlink:actuate] ,
     href, Sem.SemRoleDescrip
     FROM Sem  JOIN Loc  ON 
     Sem.SemRoleId = Loc.SemRoleId
  JOIN Slink ON Slink.link_id = Loc.link_id

1 个答案:

答案 0 :(得分:3)

一种解决方案是

  • COUNT语句添加为子查询
  • (LEFT) JOIN此子选项包含SLink表格
  • LinkCount添加到所选值列表中。

SQL语句

SELECT  Slink.[xlink:Show]
        , Loc.[xlink:show]
        , Slink.[xlink:actuate]
        , Loc.[xlink:actuate] 
        , href
        , Sem.SemRoleDescrip
        , SLinkCount.LinkCount
FROM    Sem  
        JOIN Loc ON Sem.SemRoleId = Loc.SemRoleId
        JOIN Slink ON Slink.link_id = Loc.link_id
        LEFT JOIN (
          SELECT  link_id, COUNT(*) AS LinkCount 
          FROM    Loc  
          GROUP BY 
                  link_id 
        ) SLinkCount ON SLinkCount.link_id = Slink.link_id                  

您可能希望阅读reference manual

中的子查询
  

<强> 12.2.9.8。 FROM子句中的子查询

     

子查询在SELECT语句的FROM子句中是合法的。实际上   语法是:

     

SELECT ... FROM (subquery) [AS] name ...

     

[AS] name子句是必需的,因为FROM中的每个表都是   子句必须有一个名字。子查询选择列表中的任何列都必须   有独特的名字。