Mysql SQL:如何从另一个表中按值查询表?
我的CMS里有两张桌子。其中一个包含模板变量,例如:Mysql SQL:如何从另一个表中按值查询表?,mysql,sql,inner-join,Mysql,Sql,Inner Join,我的CMS里有两张桌子。其中一个包含模板变量,例如: table: template_variables ||id||contentid||value|| ||1 ||3 ||"Some template variable"|| ||1 ||4 ||"Another template variable"|| ||2 ||5 ||"Some other template variable"|| 另一个表包含内容,重要的是,它有一个列用于显示我是否发
table: template_variables
||id||contentid||value||
||1 ||3 ||"Some template variable"||
||1 ||4 ||"Another template variable"||
||2 ||5 ||"Some other template variable"||
另一个表包含内容,重要的是,它有一个列用于显示我是否发布了该内容,例如:
table: content
||id||published||value||
||3 ||0 ||"I am not published"||
||4 ||1 ||"I am published"||
||5 ||1 ||"I am published too"||
我想做一个查询,根据相关内容是否发布,返回template\u变量的值。例如,对于上述内容,我希望返回值另一个模板变量
和另一个模板变量
,因为它们的相关内容(4和5)在内容
表中标记为已发布
我尝试过使用内部联接进行各种查询,但没有成功,例如:
SELECT `value`, `contentid` FROM `template_variables` INNER JOIN content WHERE template_variables.contentid=content.id
但是我没能让它工作——要么我的语法错误,要么结果错误
有人能为我指出正确的方向吗?您不需要连接,因为您只想使用内容表作为已发布列的参考
SELECT * from template_variables
Where contentid in
(select id from content where
published =1)
或者为了获得更好的性能,请使用存在(..)
作为
SELECT * from template_variables t
Where Exists(select 1 from content c
Where c.published=1 and
t.contentid=c.id)
请在代码问题中给出一个--cut&paste&runnable代码;示例输入(作为初始化代码)以及所需和实际输出(包括逐字错误消息);标签和版本;清晰的说明和解释。对于包含最少代码的错误,您可以给出“显示为OK”的代码,并通过“显示为not OK”的代码进行扩展。(调试基础。)用于包含DBMS和DDL的SQL,其中包括约束、索引和表格初始化。