我有这样的数据库:
例如,用户使用posts
请求所有posts.post_id = 1
数据。现在我想从其他表中获取其他数据:
posts
中包含post_id = 1
postmeta
中post_id = 1
users
中的某些字段取决于posts.user_id
post_id = 1
files
中与post_id = 1
terms
中与post_id = 1
在PHP中,我可以简单地运行5个查询来获取此信息,但我想这不是最好的方法,因为MySQL能够更快地执行此操作。
更新详细信息:
-- select from posts
SELECT
posts.post_id,
posts.post_title,
posts.post_name,
posts.post_content,
posts.post_status,
posts.post_type,
posts.post_modified_gmt,
posts.post_date_gmt,
posts.post_mime_type,
posts.user_id
FROM
posts
WHERE
posts.post_id = 1
--select from postmeta
SELECT
postmeta.postmeta_value,
postmeta.postmeta_key,
postmeta.postmeta_id
FROM
postmeta
WHERE
postmeta.post_id = 1
SELECT
files.file_size,
files.file_type,
files.file_name,
files.file_id
FROM
files
INNER JOIN file_relationships ON files.file_id = files.file_id
WHERE
file_relationships.post_id = 1
--select from terms
SELECT
terms.term_id,
terms.term_name,
terms.term_slug,
terms.term_taxonomy,
terms.term_description,
terms.term_group,
terms.term_parent,
terms.term_count
FROM
term_relationships
INNER JOIN terms ON term_relationships.term_id = terms.term_id
WHERE
term_relationships.post_id = 1
--select from users , users.user_id depend on posts.user_id
SELECT
users.user_id,
users.user_name,
users.user_email,
users.user_nicename,
users.user_password,
users.user_displayname,
users.user_role,
users.user_bio
FROM
users
WHERE
users.user_id = 1
这是我用来获取PHP信息的查询, database + data
有没有办法只使用MySQL?
答案 0 :(得分:3)
单个查询总是优于多个查询。在这种情况下,我建议仅合并您的1对1关系,但为多对1关系保留单独的查询,因为如果单个帖子有3个术语,2个文件连接多个到1个关系将产生6行。
选择帖子,用户和postmeta数据
select * from posts p
join postmeta pm on pm.post_id = p.post_id
join users u on u.user_id = p.user_id
where p.post_id = 1
选择文件
select f.* from files f
join file_relationships fr on fr.file_id = f.file_id
join posts p on p.post_id = fr.post_id
where p.post_id = 1
选择条款
select t.* from terms t
join term_relationships tr on tr.term_id = t.term_id
join posts p on p.post_id = tr.post_id
where p.post_id = 1
答案 1 :(得分:1)
这应该是您需要的所有JOIN,根据需要修改SELECT列表。
select p.post_id,
p.post_title,
p.user_id,
u.user_name,
u.user_email,
pm.*,
f.*
from posts p
join postmeta pm
on p.post_id = pm.post_id
join users u
on p.user_id = u.user_id
join file_relationships fr
on p.post_id = fr.post_id
join files f
on fr.file_id = f.file_id
*表示所有列'来自带有指定别名的表格。