我有5张桌子
Village
T1_Master (Village_ID is a foreign key)
T2_Master (Village_ID is a foreign key)
T1_Details (t1_id is a foreign key) & (month,year,t1_id are combination of primary key
(复合密钥))
T2_Details (t2_id is a foreign key) & (month,year,t2_id are combination of primary key
(复合键))
现在,如果我想要检索village_ID = 01, month=03 and year=2013
然后输出应该如下
here t1_1(No) = t1_1 has no record for month=03 and year=2013
Like wise t2_1(Yes) = t2_1 has record for month=03 and year=2013
等等......
Plz帮助我.... plz
答案 0 :(得分:0)
我认为你想要一个或多个LEFT或RIGHT JOIN:
SELECT
V.Village_ID
, Dates.[MONTH]
, Dates.[YEAR]
, CASE WHEN colValue IS NULL THEN 'no'
ELSE 'yes'
END [Yes or No]
FROM
(
SELECT
Village_ID
FROM
Villages
WHERE
Village_ID = @ParamVilageID
) V
LEFT JOIN
(
SELECT
Viilage_ID
, [MONTH]
, [YEAR]
FROM
T1_Details
WHERE
[MONTH] = @ParamMonth
AND
[YEAR] = @ParamYear
) Dates
ON V.Village_ID = Dates.Village_ID
您需要决定将哪个列引用为colValue,但所有SQL元素都在那里。 SQL将根据案例陈述推断数据类型(字符串),但您也可以返回一个直布尔值0或1
顺便说一句,拥有一个smallDate列会好得多,因为SQL有DatePart和DateName函数
答案 1 :(得分:0)
您需要使用外连接来获取空值(您可能需要考虑在左连接上找到一些可用的教程 - 很多都在谷歌上)。关键是当详细信息行不可用时使用主表来显示id。
SELECT v.Village_id,
CASE WHEN t1d.t1_id IS NULL THEN CAST(t1m.t1_id AS VARCHAR(50)) + ' (No)'
ELSE CAST(t1m.t1_id AS VARCHAR(50)) + ' (Yes)'
END T1,
CASE WHEN t2d.t2_id IS NULL THEN CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)'
ELSE CAST(t2m.t2_id AS VARCHAR(50)) + ' (Yes)'
END T2
FROM Village v
LEFT OUTER JOIN T1_Master t1m
ON t1m.Village_ID = v.Village_ID
LEFT OUTER JOIN T1_Details t1d
ON t1d.t1_id = t1m.t1_id
AND t1d.[month] = 03
AND t1d.[year] = 2013
LEFT OUTER JOIN T2_Master t2m
ON t2m.Village_ID = v.Village_ID
LEFT OUTER JOIN T2_Details t2d
ON t2d.t2_id = t2m.t2_id
AND t2d.[month] = 03
AND t2d.[year] = 2013
WHERE v.Village_ID = 01
根据数据库中的空值设置,CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)'
语句可能需要检查t2m记录是否为空以使其显示为空而不是仅显示“(否)”