[英]How to use value from one table as column name in another table in SQL query
[英]SQL: How to query table by value from another table?
我的 CMS 中有 2 个表。 一个包含模板变量,例如:
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_variables
的值。 例如上面我想返回值Another template variable
和Some other template variable
因为它们的关联内容(4 和 5)在content
表中被标记为已发布。
我已经尝试使用INNER JOIN
各种查询,但都没有成功,例如:
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)
或者为了更好的性能使用Exists(..)
作为
SELECT * from template_variables t
Where Exists(select 1 from content c
Where c.published=1 and
t.contentid=c.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.