简体   繁体   English

使用JDBC连接器在Java中的一个查询中进行多次选择

[英]Multiple selects in one query in java with jdbc connector-Mysql

I try to multiple select in java. 我尝试在Java中进行多次选择。 I have two string "name" and "artist" i want to select them both in one query even if one of them is null . 我有两个字符串“ name”和“ artist”,即使其中之一为null,我也要在一个查询中同时选择它们。

I did something like that : 我做了这样的事情:

if ( !nameIsEmpty && !artisIsEmpty )
{
    rst = stmt.executeQuery("SELECT * FROM school.product_table where name=" + "'" + name + "'  and artist=" + "'" + artist + "'");
}
else if ( nameIsEmpty && !artisIsEmpty )
{
    rst = stmt.executeQuery("SELECT * FROM school.product_table where  artist=" + "'" + artist + "'");
}
else if ( !nameIsEmpty && artisIsEmpty )
{
    rst = stmt.executeQuery("SELECT * FROM school.product_table where  name=" + "'" + name + "'");
}
else
{
    productIsEmpty = true;
}

I think its not the best way to do this. 我认为这不是最好的方法。 And I hope there is a easy way to this in one query. 我希望在一个查询中有一种简便的方法。 Thanks in advance. 提前致谢。

SELECT * FROM school.product_table where name in(name.null) and artist in (name,null) SELECT * FROM school.product_table其中name在(name.null)中,艺术家在(name,null)中

Along with matching the records with name and artist, it will also return results with name=null and artist, artist=null and name, null and null. 除了将记录与名称和艺术家匹配外,它还将返回名称为空和艺术家的艺术家,艺术家为空和名称,null和null的结果。

If you want to skip both null results try this - 如果您想同时跳过两个空结果,请尝试以下操作-

SELECT * FROM school.product_table where name in(name.null) and artist in (name,null) and !(artist=null && name=null) SELECT * FROM school.product_table其中name(null)中的名称和(name,null)中的艺术家和!(artist = null && name = null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM