如何使用primary - foreign key概念来检查多个表

时间:2013-07-17 07:37:47

标签: asp.net sql

任何人都可以帮助我一点。

我正在使用这个基本脚本来实现我的目标:

http://www.aspsnippets.com/Articles/Check-UserName-Availability-in-ASP.Net-using-JQuery.aspx

现在我想要实现的是,它应该在3个表中检查相同的用户名并确认节目:

它存在于哪个表中,而不存在。

那么如何实现这个目标,任何人都可以告诉我,我想:

创建一个表(第4个),主键为用户名,它将包含用户名。

现在在其他3个表中,我将这些表用户名作为外键,并将第4个表用户名与其链接。

现在我的问题是:要调用什么存储过程函数来实现这个目标?

2 个答案:

答案 0 :(得分:2)

select t1.Name as name1, t2.Name as name2, t3.Name as name3 from Table1 t1
full outer join Table2 t2 on t1.Name = t2.Name
full outer join Table3 t3 on t1.Name = t3.Name OR t3.Name = t2.Name

答案 1 :(得分:0)

您可以尝试以下查询。

如果您希望每个表都为行:

SELECT 'Table1' AS Tbl, COALESCE((SELECT 'Yes' FROM Table1 WHERE Name = 'Joe'),'No') AS Exist
UNION ALL
SELECT 'Table2', COALESCE((SELECT 'Yes' FROM Table2 WHERE Name = 'Joe'),'No') AS Exist
UNION ALL
SELECT 'Table3', COALESCE((SELECT 'Yes' FROM Table3 WHERE Name = 'Joe'),'No') AS Exist

或者,如果您想要单行,每个表作为列

SELECT 
   CASE WHEN t1.Name IS NULL THEN 'No' ELSE 'Yes' END as Table1
  ,CASE WHEN t2.Name IS NULL THEN 'No' ELSE 'Yes' END as Table2
  ,CASE WHEN t3.Name IS NULL THEN 'No' ELSE 'Yes' END as Table3
FROM Table1 t1
FULL JOIN Table2 t2 ON t1.Name = t2.Name
FULL JOIN Table3 t3 ON t1.Name = t3.Name OR t3.Name = t2.Name
AND t1.Name = 'Joe' AND t2.Name = 'Joe' AND t3.Name = 'Joe'

<强> SQLFiddle DEMO