我有两个表,结构如下:
Posts Table
id
content
Meta Table
id
post_id
content
name
posts 表是主要父表,可以将元表中的数据与其连接
Post Table
id content
1 My first row
Meta Table
id post_id content name
4 1 2011-5-5 date
5 1 My Heading heading
6 2 2012-3-3 date
7 2 My Title heading
我将如何编写一个查询来搜索 posts 表中的条目,该条目包含 2011-5-5 的元数据内容(名称为日期)和“我的标题”(名称为标题)
我可以单独获取它们
Select *
from posts, meta
WHERE post_id = posts.id
AND (name='date' AND content='2011-5-5')
但是一旦我添加第二个条件,它就会返回零结果,因为我们要求名称字段是两个不同的东西
Select *
from posts, meta
WHERE post_id = posts.id
AND (name='date' AND content='2011-5-5')
AND (name='heading' AND content='My Heading')
任何帮助将不胜感激,谢谢!
最佳答案
您需要加入该表两次:
SELECT *
FROM posts, meta m1, meta m2
WHERE posts.id=m1.post_id
AND posts.id=m2.post_id
AND m1.name="date" AND m1.content="2011-5-5"
AND m2.name="heading" AND m2.content="My Heading"
关于用于搜索两个表的Mysql查询结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6023918/