我在 MySQL 中有两个表:
BOOK(id int,isbn,title,publisher,author,...)
LEND(issueid,id int,enrno,dateofissue)
我想显示 BOOK
中的行
Id
不在LEND
中(即尚未发行),并且- 就像
'%s%'
我想在我的 .NET C# 应用程序 (datagridview) 中使用这个查询
我写了这个查询:
select * from book where id!=(select distinct id from lend) and title like '%" + textBox1.Text + "%';";
where textbox1.text is entered in textbox
当 LEND
为空时,此查询不显示任何行。这就是问题所在,它应该显示 BOOK
的所有行。我该如何解决这个问题?
最佳答案
!=
运算符比较两个标量值。如果您正在寻找一种方法来检查列表中是否存在特定值,您可以执行以下操作之一:
使用NOT IN
:
select *
from book where id NOT IN (
select distinct id from lend
) and title like '%" + textBox1.Text + "%' -- <<== Parameterize this!
使用NOT EXISTS
:
select *
from book where NOT EXISTS (
select id from lend where lend.id = book.id
) and title like '%" + textBox1.Text + "%' -- <<== Parameterize this!
在这两种情况下,您都应该用查询参数替换用户输入的数据。这非常重要,否则您的系统将容易受到 SQL 注入(inject)攻击。确切的语法取决于您在其中托管查询的编程语言。
关于mysql - 当一个表为空时,Select 语句不返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20132890/