简体   繁体   English

在一个查询中获取多个表

[英]fetch multiple tables in one query

This is thirty post in one houre . 这是一小时内发三十个帖子。 so i am sorry ! 所以对不起!

but i did't get what i want ! 但是我没有得到我想要的!

i will try to explain more .. 我会尽力解释更多..

i have two tables .. 我有两张桌子..

POSTS <-- my ( all site posts ) COMMENTS <-- my ( all site comments ) 帖子<-我的(所有站点帖子)评论<-我的(所有站点评论)

i want display all POSTS and COMMENTS in this one page 我想在这一页中显示所有帖子和评论

buy ( 1 query ) 买(1查询)

i have in POSTS table (100 post) and i have in COMMENTS table ( 20 comment ) 我在POSTS表中(有100条帖子),在COMMENTS表中有20条评论)

i try this code 我尝试此代码

$qq = mysql_query("SELECT posts.*,comments.* 
FROM posts LEFT JOIN comments 
ON posts.post_id = comments.post_id");
    while($tt = mysql_fetch_array($qq)){
    echo $tt['comment_title'] . '<br />'; //the title of comments !
}

in above , iam trying to print comment title 在上面,IAM试图打印评论标题

i said above i have ( 20 comments ) only ! 我在上面说我只有(20条评论)!

the code is output ( 120 comments with repeat ! ) 输出代码(120条重复的注释!)

120 is the total of the two tables ! 两个表的总数是120!

/* i want only print the 20 comments and the 100 post ( in one query ) / *我只想打印20条评论和100条帖子(在一个查询中)

How i can do that ! 我该怎么做! ?

in the end i am sorry for this more question 最后,对于这个更多的问题,我感到抱歉

but i am really need help ! 但是我真的需要帮助! my site is down 我的网站已关闭

I am assuming you need to get all posts (and by posts you mean articles) 我假设您需要获取所有帖子(而帖子指的是文章)

yes, you can use one query: 是的,您可以使用一个查询:

SELECT * FROM articles;

To get all articles 获取所有文章

<?php
$sql = "SELECT * FROM articles";
$query = mysql_query($sql);
while($result = mysql_fetch_assoc($query){
    echo $result['post_title'];
}
?>

Your question is super ambiguous, so I will do my best: 您的问题非常含糊,因此我将尽力而为:

SELECT * FROM posts LEFT JOIN comments ON posts.post_id = comments.post_id

That is the query you want (same that you have, but * instead of "posts. ,comments. ". 那就是您想要的查询(与您的查询相同,但是*而不是“ posts.comments ”。

This will, of course, retrieve all the rows in Posts, even if they don't have any comments. 当然,这将检索“帖子”中的所有行,即使它们没有任何评论。 You need to do: 您需要做:

SELECT * FROM posts LEFT JOIN comments ON posts.post_id = comments.post_id WHERE posts.post_id= = <some_id>

to get only a specific post's comments. 仅获取特定帖子的评论。 Of course, that would be silly since it would be the same thing as just doing: 当然,这将是愚蠢的,因为这与做相同的事情:

SELECT * FROM comments WHERE post_id = <some_id>

If you want to only select rows in Posts that have comments, you must do: 如果您只想选择带有评论的帖子中的行,则必须执行以下操作:

SELECT * FROM posts INNER JOIN comments ON posts.post_id = comments.post_id

Or 要么

SELECT * FROM posts NATURAL JOIN comments

(they have the same effect) (它们具有相同的效果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM