具有连接和不同的高效SQL存储过程

时间:2014-09-10 12:17:00

标签: sql-server stored-procedures join distinct

我正在努力获得一种有效的方法来执行下面的存储过程。此过程用于显示属于所有类别的市场中的企业的汽车数量。

我将类别表作为主要选择,然后我进入汽车表来统计汽车并加入他们在该类别中的业务,这里它实际上效率低下我然后检查选择的市场/位置或如果没有选择所有市场。在这里。

Create PROC  [USP_CAT]
  @MKT int

AS

BEGIN

    SELECT *,
      (
        SELECT COUNT(CAR_ID)
        FROM CARS
        INNER JOIN BUSINESS ON CAR_BIZ=BIZ_ID
        JOIN BIZCATS ON BC_BIZ = BIZ_ID AND BC_CAT = CAT_ID 
        WHERE  BIZ_APPROVED = 1 AND BIZ_EXPIRES >= getDate()  AND 
        (
          SELECT COUNT(BLOC_MKT)
          FROM BIZLOCS
          WHERE BIZ_ID = BLOC_BIZ AND (BLOC_MKT = @MKT OR @MKT = -1)
        )>0
      ) AS CAT_CAR_COUNT
    FROM CATS
    WHERE CAT_HIDE = 0
    ORDER BY CAT_ORDER asc

END

非常感谢任何对此进行整理的建议。

1 个答案:

答案 0 :(得分:0)

我认为EXISTS(http://msdn.microsoft.com/en-us/library/ms188336.aspx)可能会有所帮助。

Create PROC  [USP_CAT]
  @MKT int

AS

BEGIN

    SELECT *,
      (
        SELECT COUNT(CAR_ID)
        FROM CARS
        INNER JOIN BUSINESS ON CAR_BIZ=BIZ_ID
        JOIN BIZCATS ON BC_BIZ = BIZ_ID AND BC_CAT = CAT_ID 
        WHERE  BIZ_APPROVED = 1 AND BIZ_EXPIRES >= getDate()  AND EXISTS
        (
          SELECT BLOC_MKT
          FROM BIZLOCS
          WHERE BIZ_ID = BLOC_BIZ AND (BLOC_MKT = @MKT OR @MKT = -1)
        )
      ) AS CAT_CAR_COUNT
    FROM CATS
    WHERE CAT_HIDE = 0
    ORDER BY CAT_ORDER asc

END