我无法在SQL Server中使用JOIN从两个表中获取完整记录。
我需要ID=1
我有表格Blog
& Category
。
Blog
表:
ID BlogTitle CatID Public
--------------------------------------
1 Title One 10 1
2 Title Two 0 1
3 Title Three NULL 1
Category
表:
CatID CatName
--------------------
10 Category One
20 Category Two
查询
SELECT
ID, BlogTitle, c.CatID, CatName
FROM
Blog b
FULL OUTER JOIN
Category C ON b.CatID = c.CatID
WHERE
Public = 1 AND ID = 1
从这个查询中,我得到以下结果:
ID BlogTitle CatID CatName
----------------------------------------
1 Title One NULL NULL
虽然我期待以下结果
ID BlogTitle CatID CatName
----------------------------------------------
1 Title One 10 Category One
我做了一些尝试,但我不确定我做错了什么。
答案 0 :(得分:2)
尝试:
SELECT Blog.ID, Blog.BlogTitle, Blog.CatID, Category.CatName
FROM Blog
INNER JOIN Category
ON Blog.CatID = Category.CatID
WHERE
Blog.ID = 1
AND
Blog.Public = 1
答案 1 :(得分:1)
将条件从WHERE
移至ON
以获得外部联接结果:
SELECT ID, BlogTitle, c.CatID, CatName
FROM Blog b
FULL OUTER JOIN Category C
ON b.CatID = c.CatID
AND Public = 1 AND ID = 1
答案 2 :(得分:0)
您的ID = 1
语句中有where
,并且只有一条记录符合此条件。这就是你没有获得所有记录的原因。
尝试此操作,而不是将条件放在where
中,将其放入ON
子句中。像
SELECT ID, BlogTitle, c.CatID, CatName FROM Blog b FULL OUTER JOIN Category C ON (b.CatID = c.CatID and Public = 1 AND ID = 1)
答案 3 :(得分:0)
Use JOIN to get your result :
CREATE TABLE #table ( ID INT , BlogTitle VARCHAR(100) , CatID INT ,
_Public INT)
CREATE TABLE #table1 ( CatID INT , CatName VARCHAR(100) )
INSERT INTO #table1 ( CatID , CatName )
SELECT 10,'Category One' UNION ALL
SELECT 20,'Category Two'
INSERT INTO #table ( ID , BlogTitle , CatID , _Public )
SELECT 1,'Title One',10,1 UNION ALL
SELECT 2,'Title Two',0,1 UNION ALL
SELECT 3,'Title Three',NULL,1
SELECT ID, BlogTitle , #table.CatID , CatName
FROM #table
JOIN #table1 ON #table.CatID = #table1.CatID
WHERE Id = 1
答案 4 :(得分:0)
SELECT B.ID,B.BlogTitle,C.CatID, C.CatName FROM
(SELECT ID, BlogTitle,CatID FROM Blog WHERE Public = 1 AND ID = 1) B
FULL OUTER JOIN Category C
ON b.CatID = c.CatID