嵌套选择数据库sql查询

时间:2016-10-20 03:54:10

标签: php sql

如何订购从数据库中获取的值?

SELECT * FROM comment;
------------------------------------
| commentid | content | read_unread|
------------------------------------
1              hello      Unread
2              hi         read    


Select * From replies;
//commentid Fk from table "  comment  " so it means row 1 from table comments has 2 replies
------------------------------------
| repnum | rep_content | commentid |
------------------------------------
1              see ya        1
2              ok            1

我想在表格html / php中显示这个

comment num |  Content | replies count
--------------------------------------------------   
 1              hello    2
 2              hi       0

//“回复计数2”来自表格回复来自表评论的回复1

如何通过回复计数???

在单个查询sql命令中显示此信息

4 个答案:

答案 0 :(得分:0)

您可以在SQL查询中使用 app:layout_scrollFlags="scroll|snap"

JOIN

此处有更多信息:http://dev.mysql.com/doc/refman/5.7/en/join.html

答案 1 :(得分:0)

试试吧。

SELECT a.commentid, a.content, count(*) as replies_count
FROM comment a
LEFT JOIN replies b on a.commentid=b.commentid
GROUP BY a.commentid, a.content

答案 2 :(得分:0)

来自回复表的左连接和计数是你的好友。内部联接将删除那些尚未获得任何comments的{​​{1}},因此此处需要加入。来自replies的计数是您的要求,因此计数(*)将无效。

replies

答案 3 :(得分:0)

试试这个:

SELECT a.commentid, a.content, count(b.repnum) as replies_count 
FROM comment a left join replies b on a.commentid = b.commentid 
GROUP by a.commentid