Group by query showing some unexpected results in List view android

后端 未结 2 379
醉梦人生
醉梦人生 2021-01-24 10:22

I have a List view in which I am showing received messages from contact numbers. Now the problem was that if i received 5 messages from \"1234567\" and 3 messages from \"56789\"

相关标签:
2条回答
  • 2021-01-24 11:08
    "select * from " + "smss" +  " group by " + "contactnumber" + " = \"" + "\"" ;
    

    This is not a valid SQL-Query This Query would render to

    "select * from smss group by contactnumber = "1234567"";
    

    What's missing here is the "where" operator. Your query should include this and thus look like this:

    "select * from smss where contactnumber = "1234567" OR contactnumber = "56789" group by contactnumber";
    

    Or to display it like you did:

    "select * from " + "smss" +  " where " + "contactnumber" + " = \"" + "1234567\"" + " OR " + "contactnumber" + " = \"" + "56789\"" + " group by " + "contactnumber";
    
    0 讨论(0)
  • 2021-01-24 11:11

    You will not have these troubles if you use prepared statements. They are usually faster (if you need to do the same query multiple times), more robust and generally dont' lead to syntax errors that are hard to solve.

    PreparedStatement pstmt = con.prepareStatement( "insert into smss " +  
       "(contactnumbe,contactname,message,date)" +
       "values (?,?,?,?)";
    

    See how much simpler it is? Then you can bind the parameters one by one. NO need to worry about escaping them properly. Prepared statements take care of that for you automatically.

      stmt.setInt(msg_from.toString());
    

    and so on for each of the parameters. Getting to your GROUP by problem, I would try something like this:

    "select contactnumber, contactname, count(*) from smss group by contactnumber" ;
    

    Note that you can do SELECT * FROM smss, but the date and the messages columns are indeterminate because you are grouping by contact number. If there are multiple messages from that same number there is no assurance of which date and message will be shown. However that too can be controlled by clever use of sub queries and order by.

    0 讨论(0)
提交回复
热议问题