如何在sqlite的原始查询中使用交叉联接

时间:2018-08-04 01:38:51

标签: android sqlite

我进行了谷歌搜索,发现我也可以在SQlite Android中进行Cross Join,我已经尝试过,但是结果为空。我的程序有问题吗?或实际上交叉联接不能应用于原始查询?谢谢您的帮助。

注意:在我使用交叉联接之​​前,我尝试发送一个表(以JSONArray形式),并且该表可以工作,所以我认为在我的代码中使用交叉联接时会发生这种情况。

这是我的程序:

private JSONArray getResults()
{
    Context context = this;

    String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to your database

    //String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of your table

    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    //String searchQuery = "SELECT  * FROM " + myTable;
    Cursor cursor = myDataBase.rawQuery(" SELECT * FROM " + DatabaseHelper.ORDER_TABLE_NAME + " CROSS JOIN " + DatabaseHelper.LINEITEMS_TABLE_NAME, null );

    JSONArray resultSet     = new JSONArray();

    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {

        int totalColumn = cursor.getColumnCount();
        JSONObject rowObject = new JSONObject();

        for( int i=0 ;  i< totalColumn ; i++ )
        {
            if( cursor.getColumnName(i) != null )
            {
                try
                {
                    if( cursor.getString(i) != null )
                    {
                        Log.d("TAG_NAME", cursor.getString(i) );
                        rowObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                    }
                    else
                    {
                        rowObject.put( cursor.getColumnName(i) ,  "" );
                    }
                }
                catch( Exception e )
                {
                    Log.d("TAG_NAME", e.getMessage()  );
                }
            }
        }
        resultSet.put(rowObject);
        cursor.moveToNext();
    }
    cursor.close();
    Log.d("TAG_NAME", resultSet.toString() );


    Intent pass_data = new Intent(this,BluetoothOut.class);

    pass_data.putExtra("pindah",resultSet.toString());
    startActivity(pass_data);

    return resultSet;
}
}

这是我的数据库助手:

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="ekantins.db";

//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";

//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";




DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS " + ORDER_TABLE_NAME + " (ORDERID  INTEGER PRIMARY KEY AUTOINCREMENT,USERID TEXT ,PASSWORD TEXT, MEJA TEXT, TOPUP TEXT, SALDO TEXT)");
    db.execSQL("CREATE TABLE IF NOT EXISTS " + LINEITEMS_TABLE_NAME + " (FOODID TEXT ,PRICE TEXT, NUM TEXT, RES TEXT, ORDERID_FK INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + ORDER_TABLE_NAME ); //Drop older table if exists
    db.execSQL("DROP TABLE IF EXISTS " + LINEITEMS_TABLE_NAME ); //Drop older table if exists
    onCreate(db);
}
public void delete (String FOODID) {
    SQLiteDatabase database = this.getWritableDatabase();

    database.execSQL("DELETE FROM " + LINEITEMS_TABLE_NAME + " WHERE " + COL1 + "= '" + FOODID + "'");

    //Close the database
    database.close();
}
public String Sum() {
    SQLiteDatabase db = this.getWritableDatabase();
    String[] columns = new String[] {"SUM("+COL4+")" };
    Cursor cursor = db.query(LINEITEMS_TABLE_NAME, columns,null,null,null,null,null);
    String result = "";
    int index_SUM = cursor.getColumnIndex("SUM("+COL4+")");
    for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
        result = result + cursor.getString(index_SUM)  + "\n";
    }
    return result;
}

public String getTopup() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cr=db.rawQuery("SELECT "+COL_5+" FROM "+ORDER_TABLE_NAME,null);
    String topup="";
    for(cr.moveToFirst();!cr.isAfterLast();cr.moveToNext()){
        topup=cr.getString(cr.getColumnIndex(COL_5));
    }
    cr.close();
    return topup;
}

public String getSaldo() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cr=db.rawQuery("SELECT "+COL_6+" FROM "+ORDER_TABLE_NAME,null);
    String saldo="";
    for(cr.moveToFirst();!cr.isAfterLast();cr.moveToNext()){
        saldo=cr.getString(cr.getColumnIndex(COL_6));
    }
    cr.close();
    return saldo;
}
}

1 个答案:

答案 0 :(得分:0)

  

我的程序有问题吗?

快速浏览并不会出现。

  

还是实际上交叉联接不能应用于原始查询?

我不认为有任何此类限制。

我认为问题很简单,您在 tb_lineitems 表中没有行。因此,SELECT * FROM tb_order将返回行。但是,当您联接tb_lineitems表时,没有返回联接行。

例如使用( 请注意在注释掉SQL时如何不插入line_items ):-

DROP TABLE IF EXISTS tb_order;
CREATE TABLE IF NOT EXISTS tb_order (ORDERID  INTEGER PRIMARY KEY AUTOINCREMENT,USERID TEXT ,PASSWORD TEXT, MEJA TEXT, TOPUP TEXT, SALDO TEXT);
DROP TABLE IF EXISTS tb_lineitems;
CREATE TABLE IF NOT EXISTS tb_lineitems (FOODID TEXT ,PRICE TEXT, NUM TEXT, RES TEXT, ORDERID_FK INTEGER);
INSERT INTO tb_order VALUES
    (null,'Fred','password','meja001','topup001','saldo001'),
    (null,'Mary','password','meja002','topup002','saldo002'),
    (null,'Bert','password','meja003','topup003','saldo003');
/*
INSERT INTO tb_lineitems VALUES
    ('food001','10.30','1','res001',1),
    ('food002','11.30','1','res002',1),
    ('food002','11.30','1','res002',2)
    ;
*/
SELECT * FROM tb_order;
SELECT * FROM tb_lineitems;
SELECT * FROM tb_order 
      CROSS 
JOIN tb_lineitems 
;

产生以下3个输出:-

enter image description here enter image description here enter image description here

从插入物中删除3个tb_lineitems的注释,结果是:-

enter image description here enter image description here enter image description here

评论:-

  

我已经检查了数据库,tb_line项目和tb_order不是   空的。

您检查了哪个数据库?您正在尝试通过仔细检查代码来使用2。

在数据库帮助器中,您已将数据库定义为 ekantins.db 。但是,您可以在getResults方法中打开一个名为 ekantin1.db 的数据库。

在下面的文本中,请注意以下代码:-

    //String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to your database
    String myPath = String.valueOf(context.getDatabasePath("ekantins.db"));// Set path to your database

仅对1个数据库运行少量代码修改

  • 添加到数据库助手中的两种方法来添加订单和订单项(不包括在内)
  • 以下代码被用作活动(即您的代码+更多代码)
    • 尝试启动另一项活动的评论已被删除
    • getResults方法被两次调用,即在有任何数据之前和之后

:-

public class MainActivity extends AppCompatActivity {

    DatabaseHelper mDBHlpr;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mDBHlpr = new DatabaseHelper(this);
        JSONArray r1 = getResults();

        String sql = " SELECT * FROM " + DatabaseHelper.ORDER_TABLE_NAME + " CROSS JOIN " + DatabaseHelper.LINEITEMS_TABLE_NAME;


        cursor = mDBHlpr.getWritableDatabase().rawQuery(sql, null );
        DatabaseUtils.dumpCursor(cursor);

        // Only add data once
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.ORDER_TABLE_NAME) < 1) {

            mDBHlpr.addOrder("Fred", "password", "m001", "t001", "s001");
            mDBHlpr.addOrder("Mary", "password", "m001", "t001", "s001");
            mDBHlpr.addOrder("Bert", "password", "m001", "t001", "s001");

            cursor = mDBHlpr.getWritableDatabase().rawQuery(sql, null);
            DatabaseUtils.dumpCursor(cursor);

            mDBHlpr.addLineItem("F001", "10.30", "1", "1", 1);
            mDBHlpr.addLineItem("F002", "11.30", "2", "2", 1);
            mDBHlpr.addLineItem("F003", "12.30", "3", "3", 2);

            cursor = mDBHlpr.getWritableDatabase().rawQuery(sql, null);
            DatabaseUtils.dumpCursor(cursor);
        }

        JSONArray r2 = getResults();
    }

    private JSONArray getResults()
    {
        Context context = this;

        //String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to your database

        String myPath = String.valueOf(context.getDatabasePath("ekantins.db"));// Set path to your database

        String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of your table

        SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        //SQLiteDatabase myDataBase = mDBHlpr.getWritableDatabase();
        //String searchQuery = "SELECT  * FROM " + myTable;
        Cursor cursor = myDataBase.rawQuery(" SELECT * FROM " + DatabaseHelper.ORDER_TABLE_NAME + " CROSS JOIN " + DatabaseHelper.LINEITEMS_TABLE_NAME, null );

        JSONArray resultSet     = new JSONArray();

        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {

            int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject();

            for( int i=0 ;  i< totalColumn ; i++ )
            {
                if( cursor.getColumnName(i) != null )
                {
                    try
                    {
                        if( cursor.getString(i) != null )
                        {
                            Log.d("TAG_NAME", cursor.getString(i) );
                            rowObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                        }
                        else
                        {
                            rowObject.put( cursor.getColumnName(i) ,  "" );
                        }
                    }
                    catch( Exception e )
                    {
                        Log.d("TAG_NAME", e.getMessage()  );
                    }
                }
            }
            resultSet.put(rowObject);
            cursor.moveToNext();
        }
        cursor.close();
        Log.d("TAG_NAME", resultSet.toString() );


        /*
        Intent pass_data = new Intent(this,BluetoothOut.class);

        pass_data.putExtra("pindah",resultSet.toString());
        startActivity(pass_data);
        */

        return resultSet;
    }
}

结果是:-

08-04 07:05:36.895 1494-1494/pra.playrawaudio D/TAG_NAME: []
08-04 07:05:36.895 1494-1494/pra.playrawaudio I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@5343e554
    <<<<<
08-04 07:05:36.907 1494-1494/pra.playrawaudio I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@53441ce0
    <<<<<
08-04 07:05:36.915 1494-1494/pra.playrawaudio I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@53437acc
    0 {
       ORDERID=1
       USERID=Fred
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F001
       PRICE=10.30
       NUM=1
       RES=1
       ORDERID_FK=1
    }
    1 {
       ORDERID=1
       USERID=Fred
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F002
       PRICE=11.30
       NUM=2
       RES=2
       ORDERID_FK=1
    }
    2 {
       ORDERID=1
       USERID=Fred
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F003
       PRICE=12.30
       NUM=3
       RES=3
       ORDERID_FK=2
    }
    3 {
       ORDERID=2
       USERID=Mary
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F001
       PRICE=10.30
       NUM=1
       RES=1
       ORDERID_FK=1
    }
    4 {
       ORDERID=2
       USERID=Mary
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F002
       PRICE=11.30
       NUM=2
       RES=2
       ORDERID_FK=1
    }
    5 {
       ORDERID=2
       USERID=Mary
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F003
       PRICE=12.30
       NUM=3
       RES=3
       ORDERID_FK=2
    }
    6 {
       ORDERID=3
       USERID=Bert
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F001
       PRICE=10.30
       NUM=1
       RES=1
       ORDERID_FK=1
    }
    7 {
       ORDERID=3
       USERID=Bert
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F002
       PRICE=11.30
       NUM=2
       RES=2
       ORDERID_FK=1
    }
    8 {
       ORDERID=3
       USERID=Bert
       PASSWORD=password
       MEJA=m001
       TOPUP=t001
       SALDO=s001
       FOODID=F003
       PRICE=12.30
       NUM=3
       RES=3
       ORDERID_FK=2
    }
    <<<<<
08-04 07:05:36.919 1494-1494/pra.playrawaudio D/TAG_NAME: 1
    Fred
    password
    m001
    t001
    s001
    F001
    10.30
    1
    1
    1
08-04 07:05:36.923 1494-1494/pra.playrawaudio D/TAG_NAME: 1
    Fred
    password
    m001
    t001
    s001
    F002
    11.30
    2
    2
    1
    1
    Fred
    password
    m001
    t001
    s001
    F003
    12.30
    3
    3
    2
    2
    Mary
    password
    m001
    t001
    s001
    F001
    10.30
    1
    1
    1
    2
    Mary
    password
    m001
    t001
    s001
    F002
    11.30
    2
    2
    1
    2
    Mary
    password
    m001
    t001
    s001
    F003
    12.30
    3
    3
    2
    3
    Bert
    password
    m001
    t001
    s001
    F001
    10.30
    1
    1
    1
    3
    Bert
    password
    m001
    t001
    s001
    F002
    11.30
    2
    2
    1
    3
    Bert
    password
    m001
    t001
    s001
    F003
    12.30
    3
    3
    2
08-04 07:05:36.927 1494-1494/pra.playrawaudio D/TAG_NAME: [{"PRICE":"10.30","RES":"1","ORDERID":"1","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"1","TOPUP":"t001","FOODID":"F001","USERID":"Fred"},{"PRICE":"11.30","RES":"2","ORDERID":"1","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"2","TOPUP":"t001","FOODID":"F002","USERID":"Fred"},{"PRICE":"12.30","RES":"3","ORDERID":"1","SALDO":"s001","MEJA":"m001","ORDERID_FK":"2","PASSWORD":"password","NUM":"3","TOPUP":"t001","FOODID":"F003","USERID":"Fred"},{"PRICE":"10.30","RES":"1","ORDERID":"2","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"1","TOPUP":"t001","FOODID":"F001","USERID":"Mary"},{"PRICE":"11.30","RES":"2","ORDERID":"2","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"2","TOPUP":"t001","FOODID":"F002","USERID":"Mary"},{"PRICE":"12.30","RES":"3","ORDERID":"2","SALDO":"s001","MEJA":"m001","ORDERID_FK":"2","PASSWORD":"password","NUM":"3","TOPUP":"t001","FOODID":"F003","USERID":"Mary"},{"PRICE":"10.30","RES":"1","ORDERID":"3","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"1","TOPUP":"t001","FOODID":"F001","USERID":"Bert"},{"PRICE":"11.30","RES":"2","ORDERID":"3","SALDO":"s001","MEJA":"m001","ORDERID_FK":"1","PASSWORD":"password","NUM":"2","TOPUP":"t001","FOODID":"F002","USERID":"Bert"},{"PRICE":"12.30","RES":"3","ORDERID":"3","SALDO":"s001","MEJA":"m001","ORDERID_FK":"2","PASSWORD":"password","NUM":"3","TOPUP":"t001","FOODID":"F003","USERID":"Bert"}]
08-04 07:05:36.951 1494-1494/pra.playrawaudio I/dalvikvm: Could not find method android.view.ViewGroup$MarginLayoutParams.getLayoutDirection, referenced from method android.support.v4.view.MarginLayoutParamsCompat.getLayoutDirection

结果表明,所提供的代码或查询都没有问题。即当数据存在时返回结果