日期:2014-05-17 浏览次数:20399 次
DECLARE @TMain TABLE(MainId INT, MainName VARCHAR(32))
DECLARE @TSub TABLE(SubId INT, MainId INT, SubName VARCHAR(32), Age INT)
INSERT INTO @TMain
SELECT 1,'小明' UNION
SELECT 2,'小华' UNION
SELECT 3,'小鸟'
INSERT INTO @TSub
SELECT 11,1,'小明爸',48 UNION
SELECT 12,1,'小明妈',47 UNION
SELECT 13,1,'小明爷',69 UNION
SELECT 22,2,'小华妈',88 UNION
SELECT 23,2,'小华姐',32
--1. 查找每个有亲属的人及亲属
SELECT *
FROM @TMain a
INNER JOIN @TSub b
ON a.MainId = b.MainId
--2. 查找每个有亲属的人
SELECT *
FROM @TMain a
WHERE a.MainId IN (SELECT t.MainId
FROM @TSub t)
--3. 查找所有人及亲属
SELECT *
FROM @TMain a
LEFT JOIN @TSub b
ON a.MainId = b.MainId
--4. 查找所有人及他们当中的一位年龄最大的亲属
SELECT c.*,
t.age
FROM @TMain c
LEFT JOIN
(
SELECT b.MainId,
MAX(b.Age) AS Age,
FROM @TSub b
GROUP BY
b.MainId
) AS t
ON c.MainId = t.MainId
DECLARE @TMain TABLE(MainId INT, MainName VARCHAR(32))
DECLARE @TSub TABLE(SubId INT, MainId INT, SubName VARCHAR(32), Age INT)
INSERT INTO @TMain
SELECT 1,'小明' UNION
SELECT 2,'小华' UNION
SELECT 3,'小鸟'
INSERT INTO @TSub
SELECT 11,1,'小明爸',48 UNION
SELECT 12,1,'小明妈',47 UNION
SELECT 13,1,'小明爷',69 UNION
SELECT 22,2,'小华妈',88 UNION
SELECT 23,2,'小华姐',32
--1. 查找每个有亲属的人及亲属
SELECT *
FROM @TMain a
INNER JOIN @TSub b
ON a.MainId = b.MainId
--2. 查找每个有亲属的人
SELECT *
FROM &n