我有表catalog_view。我包含指定类别的联系人。联系人可以有几个类别。我想选择属于所有用户类别选择的联系人
e.g contact "Jone" belongs to categories [1,2,3,4,5,6] and contact "Jay" belongs to categories [1,3]. If user select categories [2,3], only "Jone" should be returned, if [1]|[3]|[1,3] selected, both should be returned, if [7]|[1,7] selected, none should be returned.
我应该如何构建查询和/或更改表来实现它?
查询按单个类别选择联系人
SELECT * FROM catalog_view WHERE (category_id = ?)
此查询选择记录,如果分配的类别与其中任何一个匹配,并返回联系人行数达到参数数量,也不会强制选择所有参数。
SELECT * FROM catalog_view WHERE (category_id = ? OR category_id = ? OR category_id =?)
此查询始终返回空表,因为catalog_view的当前模板中的行只有一个category_id
SELECT * FROM catalog_view WHERE (category_id = ? AND category_id = ? AND category_id =?)
联系人
CREATE TABLE IF NOT EXISTS contacts_table(_id integer primary key, title text default '',title_lower text default '',title_short text default '',photo blob, number text default '', note text default '', note_lower text default '', email text, partner int default '0', contact_id int default '0', current_user text default '', categories text default '', saved integer default '0' );
类别
CREATE TABLE IF NOT EXISTS categories_table(_id integer primary key, category_id integer, parent_id integer, name text, section_name text, current_user text, sub_name text default '' );
与类别的联系
CREATE TABLE IF NOT EXISTS contacts_categories_table(_id integer primary key, contact_id integer, category_id integer, current_user text );
目录查看联系人
CREATE VIEW IF NOT EXISTS catalog_view AS SELECT contacts_table._id AS _id, contacts_table.contact_id, contacts_table.title_lower, contacts_table.note_lower, contacts_table.current_user, contacts_table.saved, contacts_table.partner, contacts_table.title, contacts_table.email, contacts_table.title_short, contacts_table.number, contacts_table.note, contacts_table.categories, categories_table.section_name, contacts_table.contact_id, categories_table.parent_id, categories_table.category_id FROM contacts_categories_table INNER JOIN contacts_table ON(contacts_categories_table.contact_id = contacts_table.contact_id AND contacts_categories_table.current_user = contacts_table.current_user) LEFT OUTER JOIN categories_table ON(contacts_categories_table.category_id = categories_table.category_id AND contacts_categories_table.current_user = categories_table.current_user)
答案 0 :(得分:1)
您可以尝试以下内容:
SELECT distinct name from catalog_view s
where NUMBER_OF_CONTACT_SELECTION =
(SELECT count(*) from catalog_view t
where t.name = s.name and
category_id in(YOUR CONTACT SELECTION HERE IN FORMAT OF 1,3,4...))
因此1,3您的查询应该是:
SELECT distinct name from catalog_view s
where 2 =
(SELECT count(*) from catalog_view t
where t.name = s.name and
category_id in(1,3))
对于1,2,4,7它应该是 - > 4 =(..... IN(1,2,4,7))