从两个表中选择相同的列值

时间:2013-12-31 04:29:49

标签: mysql

我正在struts上做一个项目,我想比较两个表的行值,并希望得到匹配的列作为结果集,从结果集中我想要取出匹配的列。我正在进行以下编码,但我总是得到3作为columnsNumber。请帮我准确的结果。

public class ResultDAO {


 public int correctAnswer() throws Exception {

     int columnsNumber=0;

     Connection con=null;       
     PreparedStatement pstmt = null;

     ResultSet rs = null;
     String query="SELECT DISTINCT q1,q2,q3 FROM test WHERE (q1,q2,q3)  IN (SELECT q1,q2,q3 FROM result)ORDER BY q1,q2,q3 ASC";
     try {

         con=DatabaseConnection.getConnection();

         pstmt = con.prepareStatement(query);

         rs = pstmt.executeQuery();

         ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();

         columnsNumber = rsmd.getColumnCount();
         System.out.println(columnsNumber);


    } 
     catch (Exception e) {
         System.out.println("exception in DAO");
    }
    return columnsNumber;


 }
}

表1 :测试

列:id,q1,q2,q3值:1,A,C,C

表2 :结果

列:id,q1,q2,q3值:1,A,B,C

我正在使用此代码,但将值变为null

公共类ResultDAO {

 public String correctAnswer() throws Exception {

     String columnsNumber = null;

     Connection con=null;       
     PreparedStatement pstmt = null;

     ResultSet rs = null;
     String query="SELECT test.id,IF (test.q1 = result.q1, test.q1, NULL) as q1,IF (test.q2 = result.q2, test.q2, NULL) as q2,IF (test.q3 = result.q3, test.q3, NULL) as q3,(test.q1 = result.q1) + (test.q2 = result.q2) + (test.q3 = result.q3) as matchedColumns FROM test INNER JOIN result USING (id) ORDER BY q1,q2,q3";
     try {

         con=DatabaseConnection.getConnection();

         pstmt = con.prepareStatement(query);

         rs = pstmt.executeQuery();

         System.out.println(rs.next());
         while(rs.next()){
        columnsNumber=rs.getString("matchedColumns");


         }
         System.out.println(columnsNumber);


    } 
     catch (Exception e) {
         System.out.println("exception in DAO");
    }
    return columnsNumber;


 }

}

2 个答案:

答案 0 :(得分:1)

请尝试sqlFiddle

SELECT test.id,
       IF (test.q1 = result.q1, test.q1, NULL) as q1,
       IF (test.q2 = result.q2, test.q2, NULL) as q2,
       IF (test.q3 = result.q3, test.q3, NULL) as q3,
       (test.q1 = result.q1) + (test.q2 = result.q2) + (test.q3 = result.q3) as matchedColumns
FROM test
INNER JOIN result
USING (id)
ORDER BY q1,q2,q3

编辑:要获得不匹配的列,只需将=符号更改为此!=,然后添加另一个名为unmatchedColumns sqlFiddle的已创建列

SELECT test.id,
       IF (test.q1 = result.q1, test.q1, NULL) as q1,
       IF (test.q2 = result.q2, test.q2, NULL) as q2,
       IF (test.q3 = result.q3, test.q3, NULL) as q3,
       (test.q1 = result.q1) + (test.q2 = result.q2) + (test.q3 = result.q3) as matchedColumns,
       (test.q1 != result.q1) + (test.q2 != result.q2) + (test.q3 != result.q3) as unmatchedColumns
FROM test
INNER JOIN result
USING (id)
ORDER BY q1,q2,q3

答案 1 :(得分:0)

我假设id是结果表中的外键

 select tst.id,tst.q1,tst.q2,tst.q3,
    r.id,r.q1,r.q2,r.q3
     from test as tst
    LEFT JOIN result AS r
    ON tst.id = r.id