我有几个详细信息表的主表。我需要检查每个详细信息表是否有给定 ID 的任何行。现在我正在浏览所有表格并检查 count > 0 但必须有更好的方法。
SELECT COUNT(*) FROM Table1 WHERE ID=3;
SELECT COUNT(*) FROM Table2 WHERE ID=3;
...
SELECT COUNT(*) FROM TableN WHERE ID=3;
有没有办法在一个有效的 SQL 语句中做到这一点?
我有几个详细信息表的主表。我需要检查每个详细信息表是否有给定 ID 的任何行。现在我正在浏览所有表格并检查 count > 0 但必须有更好的方法。
SELECT COUNT(*) FROM Table1 WHERE ID=3;
SELECT COUNT(*) FROM Table2 WHERE ID=3;
...
SELECT COUNT(*) FROM TableN WHERE ID=3;
有没有办法在一个有效的 SQL 语句中做到这一点?
WITH CTE AS
(
SELECT 'T1' AS Name, COUNT(*) AS Total FROM Table1 WHERE ID=3
UNION ALL
SELECT 'T2' AS Name, COUNT(*) AS Total FROM Table2 WHERE ID=3
UNION ALL
...
UNION ALL
SELECT 'Tn' AS Name, COUNT(*) AS Total FROM TableN WHERE ID=3;
)
Select * from CTE where Total > 0
这听起来像是您的桌子设计不佳。我认为您需要合并一些表或添加一个可以查询的桥接表。
或者,如果您的结构是最佳的,并且让您的应用程序处理运行每个表,请继续查询各个表。
If you really want one result set you can do:
DECLARE @ID INT
SET @ID = 3
SELECT 'Table1' TableName, COUNT(*) FROM Table1 WHERE ID=@ID;
UNION
SELECT 'Table2' TableName, COUNT(*) FROM Table2 WHERE ID=@ID;
UNION
...
UNION
SELECT 'TableN' TableName, COUNT(*) FROM TableN WHERE ID=@ID;
I don't see a way to not scan all tables if that's what you're trying to avoid.