mysql - 当一个表为空时,Select 语句不返回任何值

标签 mysql database

我在 MySQL 中有两个表:

BOOK(id int,isbn,title,publisher,author,...)
LEND(issueid,id int,enrno,dateofissue)

我想显示 BOOK 中的行

  1. Id 不在 LEND 中(即尚未发行),并且
  2. 就像'%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/

相关文章:

mysql - 如何将 Amazon RDS mysql.slow_log 表引擎更改为 innodb

mysql - 使用mysql根据年龄过滤成员

php - 如何在 Laravel 5.7 中获取当前用户详细信息?

.net - 在 SQL 中正确使用 IN

java - JDO (Google App Engine) 中的持久列表

java - 如何在java中向弹出菜单添加多个项目?

php - 文件/图像复制

php - MySQL/Mariadb 进程在前一个进程完成之前不会运行

database - 没有任何数据库的 Infinispan 持久性?

database - 同时请求Grails org.hibernate.StaleObjectStateException