简体   繁体   English

获取一个SQL表中的数据计数与另一个SQL表的关系,并在java中使用它

[英]Obtaining a count of data from one SQL table with a relationship to another and using this in java

I have 2 database tables for my program: GameInfo and Characters. 我的程序有2个数据库表:GameInfo和Characters。 How this works is that a Game has 4 maps with different names and each character added to the game must be assigned any of the 4 maps. 这是如何工作的,游戏有4个不同名称的地图,每个添加到游戏中的角色必须分配4个地图中的任何一个。 Now I have the sql statement which returns a result set named "Expr1001, of the number of characters on each map. I then need to add this information to a jTable and link up the corresponding amount of each characterson a map, with the mapname. 现在我有一个sql语句,它返回一个名为“Expr1001”的结果集,它是每个地图上的字符数。然后我需要将这些信息添加到一个jTable中,并使用mapname链接地图上每个字符的相应数量。

My ResultSet with the query which returns the amount of characters on each map: 带有查询的ResultSet,返回每个地图上的字符数量:

ResultSet qs = dbm.queryDatabase("SELECT Expr1001 FROM (SELECT GameInfo.mapname, SUM(IIF(Map = GameInfo.mapname,1,0)) FROM (SELECT * FROM [Character] INNER JOIN Player ON Character.PlayerID=Player.[ID])  AS A RIGHT JOIN GameInfo ON A.Character.map = GameInfo.mapname GROUP BY GameInfo.mapname)  AS [%$##@_Alias]");

The whole method which gets the Game Info from the database from the GameInfo table, which comprises of a GameID and MapName only. 整个方法从GameInfo表中获取数据库中的游戏信息,该表仅包含GameID和MapName。

 public Game[] getGameInfo(){
       Game[] arr = null; //Creates an array of Games


    try { //getting list from database
        ResultSet rs = dbm.queryDatabase("Select Count(GameID) as NumGames from GameInfo" );
        //While there are still more rows to read from the database.
        rs.next();
        int count = rs.getInt("NumGames");
        arr = new Game[count];
        String sql = "Select * from GameInfo";
       // System.out.println(sql);

        rs = dbm.queryDatabase(sql);
        //Take the info from the current row
        //Add the info to the array
         ResultSet qs = dbm.queryDatabase("SELECT Expr1001 FROM (SELECT GameInfo.mapname, SUM(IIF(Map = GameInfo.mapname,1,0)) FROM (SELECT * FROM [Character] INNER JOIN Player ON Character.PlayerID=Player.[ID])  AS A RIGHT JOIN GameInfo ON A.Character.map = GameInfo.mapname GROUP BY GameInfo.mapname)  AS [%$##@_Alias]");
        for(int i = 0; rs.next(); i++){

            arr[i] = new Game(
                    rs.getInt("GameInfo.GameID"), 
                    rs.getString("GameInfo.mapname"), 
                 qs.getInt(i));
        }//Creates a Game from the currently selected info


    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Failed to get Games");
        e.printStackTrace();
    }
    return arr;
}

} }

The data is then added to the jTable which is on a Panel in the GameInfoPanel class: 然后将数据添加到GameInfoPanel类中Panel上的jTable:

 public void refreshTable() {
    //remove old stuff
    refreshing = true;

    Game[] arr = gim.getGameInfo();
    DefaultTableModel model = (DefaultTableModel) GameInfoTable.getModel();
    while (model.getRowCount() > 0) {
        model.removeRow(0);

    }
    for (int i = 0; i < arr.length; i++) {
        model.addRow(new Object[]{
            arr[i].getNumberOfCharacters(),
           arr[i].getID(),
            arr[i].getMapName()});
    }
    refreshing = false;

    //load new data from database using manager
}

I keep getting the error which points to the ResultSet qs line: "user lacks privilege or object not found: A.CHARACTER.MAP" when I try and run the program even though when I copy this statement into Microsoft Access and run it, it's fine. 我一直得到指向ResultSet qs行的错误:“当我尝试运行程序时,”我缺少权限或找不到对象:A.CHARACTER.MAP“,即使我将此语句复制到Microsoft Access并运行它,它是精细。

Help please! 请帮助! Thanks. 谢谢。

(I am still at school so not really a genius on this at all so please have mercy if I've done some stupid things) (我还在学校,所以根本不是天才,所以如果我做了一些愚蠢的事情,请怜悯)

Don't run a select count(*) first to get the number of games for allocating an array. 不要先运行select count(*)来获取分配数组的游戏数量。 Build you result in a List , which will auto-expand as needed. List构建结果, List将根据需要自动扩展。 You can always convert the list to an array later, if needed. 如果需要,您可以随后将列表转换为数组。

Don't run two queries when one can do the job, especially when you already join to the table in question. 当一个人可以完成这项工作时,不要运行两个查询,特别是当你已加入相关表时。

Your SQL is unreadable, so here it is in a more readable format: 你的SQL是不可读的,所以这里的格式更可读:

String sql = "SELECT Expr1001" +
              " FROM (SELECT GameInfo.mapname" +
                          ", SUM(IIF(Map = GameInfo.mapname,1,0))" +
                      " FROM (SELECT *" +
                              " FROM [Character]" +
                             " INNER JOIN Player ON Character.PlayerID=Player.[ID]" +
                            ")  AS A" +
                     " RIGHT JOIN GameInfo ON A.Character.map = GameInfo.mapname" +
                     " GROUP BY GameInfo.mapname" +
                    ")  AS [%$##@_Alias]";

The outer query does nothing. 外部查询什么都不做。 Get rid of it. 摆脱它。
Don't SELECT * . 不要SELECT * Select the columns you want, ie Character.map . 选择所需的列,即Character.map
Since you want GameID , add it to the GROUP BY . 由于您需要GameID ,请将其添加到GROUP BY
Specify an alias for the SUM value. SUM值指定别名。

public Game[] getGameInfo(){
    String sql = " SELECT GameInfo.GameID" +
                       ", GameInfo.mapname" +
                       ", SUM(IIF(C.map = GameInfo.mapname,1,0)) AS CharacterCount" +
                   " FROM ( SELECT Character.map" +
                            " FROM [Character]" +
                            " JOIN Player ON Player.[ID] = Character.PlayerID" +
                         ") C" +
                  " RIGHT JOIN GameInfo ON GameInfo.mapname = C.map" +
                  " GROUP BY GameInfo.GameID" +
                          ", GameInfo.mapname";
    try (ResultSet rs = dbm.queryDatabase(sql)) {
        List<Game> games = new ArrayList<>();
        while (rs.next())
            games.add(new Game(rs.getInt("GameID"),
                               rs.getString("mapname"),
                               rs.getInt("CharacterCount")));
        return games.toArray(new Game[games.size()]);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Failed to get Games");
        e.printStackTrace();
        return null;
    }
}

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

相关问题 如何使用Java在sql的表的一列中计算不同的值 - How to count different values in one column of table in sql using java 如何将数据从一个表复制到另一个表,然后使用 Java 删除第一个表中的数据? - How to copy data from one table to another and then delete that data in first table using Java? 使用Java将数据从一个oracle数据库表复制到另一数据库表 - Using Java Copy data from one oracle Database table to another database table Java SQL从另一个表动态更新一个表,不带id - Java SQL update one table dynamically from another without id 使用Java从mysql中的类型为geometry的列中获取数据 - Obtaining data from column of type geometry in mysql using java 在Hibernate中从一个表到另一个表建立关系 - Establish relationship from one table to another table in Hibernate 一个表中的SQL副本插入另一个表中-使用where子句 - SQL copy from one table insert into another - using a where clause 在Java中从mysql获取表元数据 - Obtaining Table metadata from mysql in java 如何使用Firebase使用一个表中的数据作为参考来获取另一个表中的另一数据? - How to use a data from one table as a reference to get another data in another table using Firebase? 如何使用Java将数据从一个ArrayList添加到另一个ArrayList? - How to add data from one ArrayList to another ArrayList using Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM