用于搜索两个表的Mysql查询结构
我有两个表,结构如下:
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')
任何帮助都会不胜感激,谢谢!
I have two tables sturctured like so:
Posts Table
id
content
Meta Table
id
post_id
content
name
The posts table is the main parent that can have data from the meta table joined with it
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
How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading
I can get them individually
Select *
from posts, meta
WHERE post_id = posts.id
AND (name='date' AND content='2011-5-5')
But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things
Select *
from posts, meta
WHERE post_id = posts.id
AND (name='date' AND content='2011-5-5')
AND (name='heading' AND content='My Heading')
Any help would be greatly appreciated, Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要加入该表两次:
You'll need to join to the table twice:
您需要加入元表两次(每次搜索一次) - 像这样:
You need to join to the meta table twice (once for each search) - like this:
您是否尝试过:
由于您想要将两个不同的
meta
记录与单个post
记录关联,因此您必须从meta
中进行选择两次(一次用于“日期”元值,一次用于“标题”元值)。Have you tried this:
Since there are two different
meta
records that you want to associate with a singlepost
record, you have to select frommeta
twice (once for the 'date' meta-value and once for the 'heading' meta-value).