SQL语句(SQL Server)可以工作-但它非常冗余并且效率低下。我想知道是否有一种方法可以在SELECT中定义一个case语句,然后创建条件语句。
我正在从一个表中提取信息,获取主键INT ID并检查该ID是否存在于另一个表中。如果不是,则分配一个0值-但如果确实捕获了ID。然后,我重复相同的过程以检查另一个表。
有人可以阐明如何简化此声明吗?
SELECT
a.[ID] AS ID,
a.[JOB_NUMBER] AS JOB_NUMBER,
-- Test to see if we have any entries in job_links_data, if not then assign 0
CASE WHEN
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID])) = 0
THEN 0
ELSE
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID]))
END AS JOB_LINKS,
-- If above is 0, then assign an empty string '' - else grab the title
CASE WHEN
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID])) = 0
THEN ''
ELSE
(SELECT c.[TITLE] FROM
job_links_info c,
job_links_data b,
tbl_jobs a
WHERE (b.[JOB_LINK_INFO_ID]=c.[ID] AND b.[JOB_ID]=a.[ID]))
END AS TITLE
FROM tbl_jobs a
WHERE (
a.[PROJECT_ID]=25
);
答案 0 :(得分:1)
这似乎很愚蠢:
CASE WHEN
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID])) = 0
THEN 0
ELSE
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID]))
END AS JOB_LINKS,
如果值为0,则分配0?替换为:
(SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID])) AS JOB_LINKS
我还建议您使用正确的,明确的,标准 JOIN
语法。 从不在FROM
子句中使用逗号。
答案 1 :(得分:1)
您应该考虑声明一个变量并在查询中使用它,如下所示:
DECLARE @JOB_LINKS int
SET @JOB_LINKS = (SELECT COUNT([ID]) FROM job_links_data WHERE ([JOB_ID]=a.[ID]))
-- And after this, your query with the variable.
SELECT
a.[ID] AS ID,
a.[JOB_NUMBER] AS JOB_NUMBER,
@JOB_LINKS AS JOB_LINKS,
CASE WHEN @JOB_LINKS = 0
THEN ''
ELSE -- selecting the title only when job links is not 0
(SELECT c.[TITLE] FROM
job_links_info c,
job_links_data b,
tbl_jobs a
WHERE (b.[JOB_LINK_INFO_ID]=c.[ID] AND b.[JOB_ID]=a.[ID]))
END AS TITLE
FROM tbl_jobs a
WHERE (
a.[PROJECT_ID]=25
);
必须在语句前设置变量 ,但这并非总是可能的,具体取决于您执行查询的方式。