【发布时间】:2020-03-24 18:53:03
【问题描述】:
使用 mysql 5.7,我想查询article 表中具有最相似tag 列的行:
CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`body` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`slug` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`lasthit` datetime DEFAULT CURRENT_TIMESTAMP,
`tag1` varchar(100) NOT NULL DEFAULT 'NA',
`tag2` varchar(100) NOT NULL DEFAULT 'NA',
`tag3` varchar(100) NOT NULL DEFAULT 'NA',
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`)
) ENGINE=InnoDB AUTO_INCREMENT=10800 DEFAULT CHARSET=utf8
这是我的查询:
SELECT newA.title, newA.slug, newA.tag1, newA.tag2, newA.tag3
FROM article a
JOIN article newA
ON newA.tag1 IN (a.tag1, a.tag2, a.tag3) OR
newA.tag2 IN (a.tag1, a.tag2, a.tag3) OR
newA.tag3 IN (a.tag1, a.tag2, a.tag3)
WHERE a.id = 242
AND newA.id != a.id
ORDER BY
(newA.tag1 IN (a.tag1, a.tag2, a.tag3) IS NOT NULL) +
(newA.tag2 IN (a.tag1, a.tag2, a.tag3) IS NOT NULL) +
(newA.tag3 IN (a.tag1, a.tag2, a.tag3) IS NOT NULL)
DESC
LIMIT 10;
我想排除标记长度小于 2 个字符的结果,以便不相关的项目(标记列为空或仅包含 NA 的项)不会潜入。
我所做的是将AND LEN(a.tag1)>2 AND LEN(a.tag2)>2 AND LEN(a.tag3)>2 添加到WHERE 子句,但随后我得到很多Display all 1333 possibilities? (y or n) 而不是结果。
我也试过
...
ON (newA.tag1 IN (a.tag1, a.tag2, a.tag3) OR
newA.tag2 IN (a.tag1, a.tag2, a.tag3) OR
newA.tag3 IN (a.tag1, a.tag2, a.tag3)) AND
(LEN(a.tag1)>2 AND LEN(a.tag2)>2 AND LEN(a.tag3)>2)
...
然后我明白了
ERROR 1305 (42000): FUNCTION myawsomedb.LEN does not exist
我该如何解决这个问题?
【问题讨论】:
-
最相似的 这不是一个非常具体的标准。你能把它限定为特定的东西吗
-
这是这个问题的后续:stackoverflow.com/questions/60825512/… 我在这里更详细地解释了我的目标。
-
在
WHERE子句中添加AND条件只能减少选择的行数,不能增加。 -
@RiggsFolly 这就是
ORDER BY所做的——它将匹配的标签数量相加。 -
MySQL 不知道 LEN() - 它知道 LENGTH()。