以下是回答理解系统所需的表格和数据的转储: -
该系统由导师和班级组成。 表All_Tag_Relations中的数据存储了每个注册的教师和由教师创建的每个班级的标签关系。标签关系用于搜索类。
CREATE TABLE IF NOT EXISTS `Tags` (
`id_tag` int(10) unsigned NOT NULL auto_increment,
`tag` varchar(255) default NULL,
PRIMARY KEY (`id_tag`),
UNIQUE KEY `tag` (`tag`),
KEY `id_tag` (`id_tag`),
KEY `tag_2` (`tag`),
KEY `tag_3` (`tag`),
KEY `tag_4` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `Tags` (`id_tag`, `tag`) VALUES
(1, 'Sandeepan'),
(2, 'Nath'),
(3, 'first'),
(4, 'class'),
(5, 'new'),
(6, 'Bob'),
(7, 'Cratchit');
CREATE TABLE IF NOT EXISTS `All_Tag_Relations` (
`id_tag` int(10) unsigned NOT NULL default '0',
`id_tutor` int(10) default NULL,
`id_wc` int(10) unsigned default NULL,
KEY `All_Tag_Relations_FKIndex1` (`id_tag`),
KEY `id_wc` (`id_wc`),
KEY `id_tag` (`id_tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `All_Tag_Relations` (`id_tag`, `id_tutor`, `id_wc`) VALUES
(1, 1, NULL),
(2, 1, NULL),
(3, 1, 1),
(4, 1, 1),
(6, 2, NULL),
(7, 2, NULL),
(5, 2, 2),
(4, 2, 2),
(8, 1, 3),
(9, 1, 3);
以下是我的查询:
此查询在Tags表中搜索“first class”(first = 3和class = 4的标记)并返回所有这些类,使得类名称中的first和class都存在。
SELECT wtagrels.id_wc,SUM(DISTINCT( wtagrels.id_tag =3)) AS
key_1_total_matches,
SUM(DISTINCT( wtagrels.id_tag =4)) AS
key_2_total_matches
FROM all_tag_relations AS wtagrels
WHERE ( wtagrels.id_tag =3
OR wtagrels.id_tag =4 )
GROUP BY wtagrels.id_wc
HAVING key_1_total_matches = 1
AND key_2_total_matches = 1
LIMIT 0, 20
它返回id_wc = 1的类。
但是,我希望搜索显示所有这些类,以便所有搜索字词都出现在类名或其导师名称中 因此,搜索“Sandeepan class”(wtagrels.id_tag = 1,4)或“Sandeepan Nath”也会返回id_wc = 1的类。和搜索。搜索“Bob First”不应该返回任何类别。
如果可能,请修改上述查询或建议新查询,使用MyIsam - 全文搜索,但不知何故可以帮助我获得结果。
答案 0 :(得分:1)
我认为这个查询可以帮到你:
SET @tag1 = 1, @tag2 = 4; -- Setting some user variables to see where the ids go. (you can put the values in the query)
SELECT wtagrels.id_wc,
SUM(DISTINCT( wtagrels.id_tag =@tag1 OR wtagrels.id_tutor =@tag1)) AS key_1_total_matches,
SUM(DISTINCT( wtagrels.id_tag =@tag2 OR wtagrels.id_tutor =@tag2)) AS key_2_total_matches
FROM all_tag_relations AS wtagrels
WHERE ( wtagrels.id_tag =@tag1 OR wtagrels.id_tag =@tag2 )
GROUP BY wtagrels.id_wc
HAVING key_1_total_matches = 1 AND key_2_total_matches = 1
LIMIT 0, 20
返回id_wc = 1
对于(6,3),查询不返回任何内容。