我正在开发一个Android应用程序,我正在使用CursorAdapter显示带有Name和CheckBox的TextView,如果他们有这个项目。我的问题是管理游标,因为你可以看到有时名称是重复的。
我有两张桌子:
表A:
_id | Name | Attend 1 --- John ---- 1 2 --- Peter --- 1 3 --- Jean ---- 0 4 --- Finn ---- 1 5 --- Jake ---- 1
表B:
_id | _idA | Item 12 --- 1 ---- Yogurt 21 --- 2 ---- Yogurt 33 --- 1 ---- Wine 25 --- 2 ---- KitKat
我正在寻找具有以下条件的JOIN表: Attend = 1,Item = Yogurt和表A中的所有名字不重复,这是我要找的结果:
Id | Name | Attend | _id | _idA | Item 1 -- John ----- 1 ----- 12 --- 1 --- Yogurt 2 -- Peter ---- 1 ------ 21 -- 2 --- Yogurt 4 -- Finn ----- 1 5 -- Jake ----- 1
我正在使用此查询,但我不知道我是否处于良好状态。我曾尝试使用Group by或WHERE Item = Yogurt,但我找不到解决方案,不要让名字重复
SELECT * FROM TableA as A LEFT OUTER JOIN TableB AS B ON A._id = B._idA
结果是:
Id | Name | Attend | _id | _idA | Item 1 -- John ---- 1 ------- 12 --- 1 --- Yogurt 1 -- John ---- 1 ------- 33 --- 1 --- Wine 2 -- Peter --- 1 ------- 21 --- 2 --- Yogurt 2 -- Peter --- 1 ------- 35 --- 2 --- KitKat 4 -- Finn ---- 1 5 -- Jake ---- 1
答案 0 :(得分:1)
你说你想要条件" Item = Yogurt",但事实并非如此。 您要查找的结果包含Item列具有另一个值(NULL)的行。
如果要获取Finn / Jake行,则必须编写与这些行匹配的WHERE子句:
SELECT *
FROM TableA as A
LEFT OUTER JOIN TableB AS B ON A._id = B._idA
WHERE A.Attend
AND (B.Item = 'Yogurt' OR B.Item IS NULL);
或者,将此条件放入外连接子句中,如果没有连接记录,它将被忽略:
SELECT *
FROM TableA as A
LEFT OUTER JOIN TableB AS B ON A._id = B._idA
AND B.Item = 'Yogurt'
WHERE A.Attend;