Php 需要关于从数据库检索数据的建议吗
我有一个MySQL数据库,有两个表。 第一张表:Php 需要关于从数据库检索数据的建议吗,php,mysql,database,Php,Mysql,Database,我有一个MySQL数据库,有两个表。 第一张表: Posts ID post_title post_content ... etc 第二个表中包含其他数据: Postmeta ID Post_ID (FK) meta_key meta_value 我需要的数据在meta_键/值对中。但是这个数据库的组织方式是,第二个表中的每一行只有
Posts
ID
post_title
post_content
... etc
第二个表中包含其他数据:
Postmeta
ID
Post_ID (FK)
meta_key
meta_value
我需要的数据在meta_键/值对中。但是这个数据库的组织方式是,第二个表中的每一行只有一条信息
SELECT * FROM Posts, Postmeta
WHERE Posts.Post_id = Postmeta.Post_id
GROUP BY Posts.Post_id
例如(第二个表):
所以如果我运行查询
SELECT
posts.id,
posts.post_date,
posts.post_author,
posts.post_content,
posts.post_title,
postmeta.meta_id,
postmeta.meta_key,
postmeta.meta_value
FROM posts INNER JOIN postmeta ON posts.id = postmeta.post_id
WHERE posts.post_type = 'post'
我得到了我需要的所有数据,但第一个表中的数据(ID/post_内容等)重复了很多次。
但我只需要第一个表中的数据一次,但需要第二个表中与第一个表的ID相关的所有附加数据
我该怎么过滤这些东西?可能是一些php循环?您可以使用如下函数:
select
posts.id,
posts.post_date,
posts.post_author,
posts.post_content,
posts.post_title,
group_concat(postmeta.meta_id) as metaID,
group_concat(postmeta.meta_key) as metaKey,
group_concat(postmeta.meta_value_ as metaValue
from
posts
INNER JOIN postmeta
ON posts.id = postmeta.post_id
where
posts.post_type = 'post'
group by
posts.id,
posts.post_date,
posts.post_author,
posts.post_content,
posts.post_title
要在PHP中拆分结果,您可以轻松使用explode函数来形成结果信息的数组。使用
选择DISTINCT
而不仅仅是选择您应该使用发布的查询获取所有数据,然后在PHP应用程序中以您想要的格式输出,其中,第一个表中的每个数据都是第二个表中相应项目的标题。您不应该在SQL中格式化数据,它不用于格式化数据。
SELECT * FROM Posts, Postmeta
WHERE Posts.Post_id = Postmeta.Post_id
GROUP BY Posts.Post_id