这是表格的结构
CREATE TABLE Book_Tag (id INT, Book_Id INT, tag varchar(20))
CREATE TABLE Book_Master (Book_Id INT, Book_title VARCHAR(50), price INT)数据看起来如下:
INSERT INTO Book_Master
SELECT 1, 'Good Profit', 28 UNION ALL
SELECT 2, 'The Secret', 20 UNION ALL
SELECT 3, 'The One Minute Manager', 9 UNION ALL
SELECT 4, 'The 7 Habits of Highly Effective People', 35 UNION ALL
SELECT null, 'Who Moved My Cheese?', 15 UNION ALL
SELECT null, 'Blink: The Power of Thinking Without Thinking', 40
INSERT INTO Book_Tag
SELECT 1, 1, 'Management' UNION ALL
SELECT 2, 1, 'Profit' UNION ALL
SELECT 3, 2, 'Mind' UNION ALL
SELECT 4, 3, 'Management' UNION ALL
SELECT 5, 3, 'Efficiency' UNION ALL
SELECT 6, 3, 'Success' UNION ALL
SELECT 7, 4, 'Success' UNION ALL
SELECT 8, null, 'Time' UNION ALL
SELECT 9, 6, 'SelfHelp' UNION ALL
SELECT 10, 6, 'Motivation' UNION ALL
SELECT 11, 8, 'Mind'select * from Book_Master
Book_Id Book_title price
1 Good Profit 28
2 The Secret 20
3 The One Minute Manager 9
4 The 7 Habits of Highly Effective People 35
NULL Who Moved My Cheese? 15
NULL Blink: The Power of Thinking Without Thinking 40select * from Book_Tag
id Book_Id tag
1 1 Management
2 1 Profit
3 2 Mind
4 3 Management
5 3 Efficiency
6 3 Success
7 4 Success
8 NULL Time
9 6 SelfHelp
10 6 Motivation
11 8 Mind我不知道为什么以下是有效的,也不知道为什么结果是这样。
select BT.* from Book_Tag BT
where BT.Book_Id in (select id)
id Book_Id tag
1 1 Management或者这个
select BT.* from Book_Tag BT
where BT.Book_Id not in (select id)
id Book_Id tag
2 1 Profit
3 2 Mind
4 3 Management
5 3 Efficiency
6 3 Success
7 4 Success
9 6 SelfHelp
10 6 Motivation
11 8 Mind发布于 2017-06-28 18:38:53
您的第一个查询:
select BT.*
from Book_Tag BT
where BT.Book_Id in (select id); 它与以下内容相同:
select BT.*
from Book_Tag BT
where BT.Book_Id = BT.id;所以你才能
1 1 Management
请记住,NULL并不等于NULL或其他任何东西。
在第二个例子中,您有:
select BT.*
from Book_Tag BT
where BT.Book_Id not in (select id);这与以下相同:
select BT.*
from Book_Tag BT
where BT.Book_Id <> BT.id;注意,没有8 NULL Time行。
编辑:
但是,在Subquery中,我们不应该指定id来自的表吗?
来自MSDN
一般规则是,语句中的列名由FROM子句中引用的表在同一级别隐式限定。如果子查询的FROM子句中引用的表中不存在列,则该列由外部查询的FROM子句中引用的表隐式限定。
和
如果在子查询中引用的列不存在于子查询的FROM子句引用的表中,而是存在于外部查询的FROM子句引用的表中,则查询将无错误地执行。Server隐式地限定子查询中的列与外部查询中的表名。。
发布于 2017-06-28 18:23:53
您在这里问“BT.Book_Id in (select ID )在哪里”,意思是Book_ID =ID,所以在本例中它打印出来了。Book_ID和ID都是1,那么,当它们不相等时就不是了,这是表中的其他所有内容。
https://stackoverflow.com/questions/44809882
复制相似问题