你好我在mysql表中有2个表和post_meta表 我想根据post_meta键/值数据查询post表。 带有= statment的示例中的第一个查询正在运行,第二个查询带有!= statment无法正常工作。有帮助吗?
如何排除包含postmeta键的帖子[hide] = value ['1']?
这里有期待的结果
例如
//显示postmeta键[hide] = value 1
的帖子SELECT
*
FROM
post AS mt0
INNER JOIN post_meta AS mt1 ON mt0.id = mt1.postid
WHERE
(
mt1.`key` = 'hide'
AND CAST(mt1.`value` AS CHAR) = 1
)
2行
1后测试1 3 1隐藏1
3后测试3 4 3隐藏1
//显示postmeta键的位置[hide]!= value 1
SELECT
*
FROM
post AS mt0
INNER JOIN post_meta AS mt1 ON mt0.id = mt1.postid
WHERE
(
mt1.`key` = 'hide'
AND CAST(mt1.`value` AS CHAR) != 1
)
0行
//为什么呢?此查询必须返回帖子2
数据库架构
----table post
CREATE TABLE `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `post` VALUES ('1', 'Post test 1');
INSERT INTO `post` VALUES ('2', 'Post test 2');
INSERT INTO `post` VALUES ('3', 'Post test 3');
----table post_meta
CREATE TABLE `post_meta` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`postid` int(11) DEFAULT NULL,
`key` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `post_meta` VALUES ('1', '1', 'name', 'leone');
INSERT INTO `post_meta` VALUES ('2', '2', 'name', 'mario');
INSERT INTO `post_meta` VALUES ('3', '1', 'hide', '1');
INSERT INTO `post_meta` VALUES ('4', '3', 'hide', '1');
答案 0 :(得分:3)
由于条件
,第二个查询不起作用mt1.`key` = 'hide'
仔细查看查询
SELECT
*
FROM
post AS mt0
INNER JOIN post_meta AS mt1 ON mt0.id = mt1.postid
WHERE
(
mt1.`key` = 'hide'
AND CAST(mt1.`value` AS CHAR) != 1
)
您的条件为
mt1.`key` = 'hide'
然后你正在使用
AND CAST(mt1.`value` AS CHAR) != 1
现在在post_meta
表格中检查没有数据
key = hide and value != '1'
因此条件失败,你得到0结果
以下是您提供的内容
INSERT INTO `post_meta` VALUES ('1', '1', 'name', 'leone');
INSERT INTO `post_meta` VALUES ('2', '2', 'name', 'mario');
INSERT INTO `post_meta` VALUES ('3', '1', 'hide', '1');
INSERT INTO `post_meta` VALUES ('4', '3', 'hide', '1');
根据问题中提供的更新,您可以获得结果
SELECT *
FROM
post AS mt0
INNER JOIN post_meta mt1
ON mt0.id = mt1.postid
AND mt0.id NOT IN (
select postid from post_meta where `key` = 'hide' AND CAST(`value` AS CHAR) = 1
);
<强> DEMO 强>