MySQL:组合两个重复查询


MySQL: Combining two repetitive queries

我在一个表格中的信息中有这个,有时pd_idNULL

doc_id  doc_title   doc_order   pg_id 
14      a.zip       1           NULL    
15      b.zip       2           NULL    
12      c.zip       1           16  
13      d.zip       2           16      
3       f.doc       3           16      
4       g.doc       4           16  

当我想查询带有 pg_id 16 的项目时,我这样做,

SELECT * 
FROM root_documents 
WHERE root_documents.pg_id = '16'

当我想在没有任何pd_id的情况下查询项目时,我这样做,

SELECT * 
FROM root_documents 
WHERE root_documents.pg_id IS NULL

我发现两个查询是重复的,所以我尝试这样做,

SELECT * 
FROM root_documents 
WHERE (root_documents.pg_id = ? OR root_documents.pg_id IS NULL)

因此,当我只想在查询pg_id 16 的项目时获得此结果时,

doc_id  doc_title   doc_order   pg_id 
12      c.zip       1           16  
13      d.zip       2           16      
3       f.doc       3           16      
4       g.doc       4           16

但是我把他们都弄进去了!

doc_id  doc_title   doc_order   pg_id 
14      a.zip       1           NULL    
15      b.zip       2           NULL    
12      c.zip       1           16  
13      d.zip       2           16      
3       f.doc       3           16      
4       g.doc       4           16

我该如何解决此查询,

SELECT * 
FROM root_documents 
WHERE (root_documents.pg_id = ? OR root_documents.pg_id IS NULL)

还是我必须像往常一样重复查询?

编辑:

当我有一个参数要传递到占位符中时,这个答案对我来说看起来很奇怪:

SELECT * FROM root_documents WHERE (root_documents.pg_id = '16' OR (root_documents.pg_id IS NULL AND '16' IS NULL))

当没有参数时,

SELECT * FROM root_documents WHERE (root_documents.pg_id = NULL OR (root_documents.pg_id IS NULL AND NULL IS NULL))

请注意,当未返回任何值时,我将NULL传递到placeholder中。

抱歉:您正在使用 MYSQL...无视。

一种方法是这样的:

SELECT * 
FROM root_documents 
WHERE isnull(root_documents.pg_id, -1) = ?

-1 或任何您不希望在 [root_documents.pg_id] 中找到的值。然后,当您要搜索 NULL 查询该值时。

我想你想要这样的东西:

SELECT * 
FROM root_documents 
WHERE (root_documents.pg_id = ? OR (root_documents.pg_id IS NULL AND ? IS NULL))
当您

需要该pg_id时,您可以将 ? 设置为数字,或者当您想要 null 时设置为 IS NULL 字符串。

我认为以下内容应该适合您(更新(:

SELECT * 
FROM root_documents r1
WHERE (r1.pg_id = ? 
OR (NOT EXISTS 
 (SELECT * FROM FROM root_documents r2 
  WHERE r2.pg_id = ? )
 AND r1.pg_id IS NULL)