我目前在存储过程中有以下代码(见下文)。为了总共获得10个结果,我拿下了每个联盟的前五名。但是,我想取UNION的前10名,而不是每个中的5名。有任何想法吗?这可能吗?
BEGIN
SELECT TOP 5
a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
UNION ALL
SELECT TOP 5
b_object_ID as [id],
b_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_b]
WHERE b_object_name LIKE @Search + '%'
ORDER BY [name]
END
答案 0 :(得分:2)
是的,非常可能。您只需从联合结果中选择前10名。
SELECT TOP 10 * FROM (
SELECT
a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
UNION ALL
SELECT
b_object_ID as [id],
b_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_b]
WHERE b_object_name LIKE @Search + '%'
) u
ORDER BY u.[name]
答案 1 :(得分:2)
使您的UNION成为子查询
SELECT TOP 10 *
FROM (
SELECT
a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
UNION ALL
SELECT
b_object_ID as [id],
b_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_b]
WHERE b_object_name LIKE @Search + '%'
) AS subquery
ORDER BY subquery.[name]
答案 2 :(得分:1)
这个怎么样?
SELECT TOP 10 *
FROM
(
SELECT a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
UNION ALL
SELECT b_object_ID as [id],
b_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_b]
WHERE b_object_name LIKE @Search + '%'
) x
ORDER BY [name]
答案 3 :(得分:1)
为什么要使查询复杂化?这将完成这项工作:
set rowcount 10
SELECT a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
UNION ALL
SELECT b_object_ID as [id],
b_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_b]
WHERE b_object_name LIKE @Search + '%'
ORDER BY [name]
set rowcount 0
答案 4 :(得分:0)
上述答案是浪费的,因为子查询收集然后拒绝可能大量的行。您可以使用子查询改进问题。
declare @Recs int = 10;
with cte1 as (
SELECT TOP (@Recs)
a_object_ID as [id],
a_object_name as [name],
'A_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
)
, cte2 as
(
SELECT TOP (@Recs)
a_object_ID as [id],
a_object_name as [name],
'B_object' as [Type]
FROM [database].[dbo].[table_a]
WHERE a_object_name LIKE @Search + '%'
)
SELECT TOP (@Recs) [id], [name], [Type]
(
select [id], [name], [Type] from cte1
union all
select [id], [name], [Type] from cte2
) SQ
ORDER BY [Name]