简体   繁体   English

连接两个表以计数

[英]Joining two tables to get a count

I am attempting to count comments on a particular page with the following problematic sql query: 我正在尝试使用以下有问题的sql查询来计数特定页面上的注释:

$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND page_id = '943'"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;

the problem is it is outputting 0 and not 2. 问题是它输出0而不是2。

The tables are as follows: 下表如下:

pages: 页面:

id:1 page_id:943

id:2 page_id:978

id:3 page_id:977

comments: 评论:

id:2 page_id:1 "hello"

id:3 page_id:1 "great"

id:4 page_id:3 "super"

So really the original query should be getting each comment's true page_id from the page_id as set in the pages tables, as joined by comments.page_id = pages.id 因此,实际上,原始查询应该从页面表中设置的page_id获取每个评论的真实 page_id ,并由comments.page_id = pages.id

What would the final code look like to either make that join, and/or get that count? 最终的代码将成为什么样的子,或者使之加入和/或获得该计数? Thank you. 谢谢。

"SELECT * FROM comments, pages WHERE comments.page_id = pages.id AND is_approved = '1' AND comments.page_id = '943'"

Try: 尝试:

SELECT c.* FROM `comments` c
JOIN `pages` p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'

Try using: 尝试使用:

SELECT count(*) as cnt
FROM `comments` c join pages p on c.page_id =  p.id
WHERE c.is_approved = '1' AND p.page_id = '943'

It seems like a very poor database design to have two columns with the same name in different tables that mean different things. 在不同的表中包含两个具有相同名称的列似乎意味着不同的事情,这似乎是一个非常糟糕的数据库设计。 You should probably change the name of pages.page_id to something else. 您可能应该将pages.page_id的名称更改为其他名称。

And, this returns the count directly, so you can read the value from the row. 并且,这将直接返回计数,因此您可以从行中读取值。 If you just want the count, there is no reason to return all the matching rows. 如果只需要计数,则没有理由返回所有匹配的行。

no join is needed: 无需加入:

$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;

ofcourse i would suggest a count statement if you do not need/use the data: 当然,如果您不需要/使用数据,我建议您使用count语句:

$query = "SELECT COUNT(*) as total FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$total = $row['total'];
echo $total;

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

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