使用多个WHERE条件从表中检索多个值

时间:2013-01-21 15:34:20

标签: mysql sql select jdbc

我在MYSQL数据库中有这个表(见附图)

database

我想找回三个不同公寓的“电缆”栏。这是我到目前为止在我的代码中所拥有的,但它不起作用,任何想法为什么?

try
{
        //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        //Connection connection=DriverManager.getConnection("jdbc:odbc:db1","","");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_VecinetSM?user=etoolsco&password=g7Xm2heD41");
        Statement statement=connection.createStatement();
        String query;
        query="SELECT cable FROM flatene2013 WHERE Apto='5C' JOIN SELECT cable FROM flatene2013 WHERE Apto='5Cest1' JOIN SELECT cable FROM flatene2013 WHERE Apto='5Cest2'";            
        ResultSet resultSet=statement.executeQuery(query);
        while(resultSet.next())
    {%>
    <tr>

    <td>&nbsp;</td>
    <td align="right"><font size="-1"><%out.println(resultSet.getBigDecimal(1)+"");%></font></td>
    <td align="right"><font size="-1"><%out.println(resultSet.getBigDecimal(2)+"");%></font></td>
    <td align="right"><font size="-1"><%out.println(resultSet.getBigDecimal(3)+"");%></font></td>
    </tr>
    <%
    }

2 个答案:

答案 0 :(得分:2)

使用UNION代替JOIN

SELECT  cable , Apto
FROM    flatene2013 
WHERE   Apto='5C' 
UNION
SELECT  cable , Apto 
FROM    flatene2013 
WHERE   Apto='5Cest1' 
UNION
SELECT  cable  , Apto
FROM    flatene2013 
WHERE   Apto='5Cest2'

或者如果您不介意Apto

SELECT  cable , Apto
FROM    flatene2013 
WHERE   Apto IN ('5C' , '5Cest1', '5Cest2')

<强>更新

SELECT  MAX(CASE WHEN Apto = '5C' THEN  Cable ELSE NULL END) as `5c`,
        MAX(CASE WHEN Apto = '5Cest1' THEN  Cable ELSE NULL END) as `5Cest1`,
        MAX(CASE WHEN Apto = '5Cest2' THEN  Cable ELSE NULL END) as `5Cest2`
FROM
        (
            SELECT  cable , Apto
            FROM    flatene2013 
            WHERE   Apto IN ('5C' , '5Cest1', '5Cest2')
        ) s

答案 1 :(得分:1)

尝试使用WHERE IN:

SELECT cable FROM flatene2013 WHERE Apto IN ('5C','5Cest1','5Cest2')