我该如何编写此查询?

时间:2013-03-05 11:22:17

标签: android sqlite android-sqlite

我有两个表Y和X.Y的每个项目都可以有很多Xi这样:

Y   X
--  --
A   X1  √
B   X1
B   X2
B   X3
C   X2
D   X1
D   X2
E   X1  √

我希望Ys只有刻度显示的X1。 什么是查询?

我应该提一下,我的数据库是Android Sqlite。

Select * 
From Y 
Inner join X 
on Y.id = X.Yid 
where X.id is only X1 and nothing else

如何通过is only X1 and nothing else

编写等效的实际查询

3 个答案:

答案 0 :(得分:1)

换句话说,您希望拥有Y但没有任何其他X1的所有X。在SQL中:

SELECT *
FROM Y
WHERE EXISTS (SELECT X.id
              FROM X
              WHERE X.id = Y.Xid
                AND X.name = 'X1')
  AND NOT EXISTS (SELECT X.id
                  FROM X
                  WHERE X.id = Y.Xid
                    AND X.name != 'X1')

或者,第一个子查询可以写为连接:

SELECT Y.*
FROM Y JOIN X
       ON Y.Xid = X.id
WHERE X.name = 'X1'
  AND NOT EXISTS (SELECT X2.id
                  FROM X AS X2
                  WHERE X2.id = Y.Xid
                    AND X2.name != 'X1')

答案 1 :(得分:0)

查询可以是:

 Select * 
  From Y 
  inner join X 
 on Y.Xid = X.id 
  where X.id = 'X1'

答案 2 :(得分:0)

Cursor c = sampleDB.rawQuery("SELECT * FROM " +
            Y +
            " where X=x1", null);

    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String yarray[] = c.getString(c.getColumnIndex("Y"));
            }while (c.moveToNext());
        }
    }

Now yarray[] will contain all your y values