Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何连接这些表?_Php_Mysql_Sql - Fatal编程技术网

Php 如何连接这些表?

Php 如何连接这些表?,php,mysql,sql,Php,Mysql,Sql,我有三张桌子: users ----------------------------------- id | firstname | lastname | username ----------------------------------- 1 | John | Doe | jdoe ----------------------------------- 2 | Maria | T. | marty --------------------------

我有三张桌子:

users
-----------------------------------
id | firstname | lastname | username
-----------------------------------
1  | John     | Doe      | jdoe
-----------------------------------
2  | Maria    | T.       | marty
-----------------------------------
3  | Alex     | White    | alexw
-----------------------------------

questions
--------------------------------------------
id | user_id | title
--------------------------------------------
1  | 2       | My first question?
--------------------------------------------
2  | 3       | One more question?
--------------------------------------------
3  | 3       | The third question?
--------------------------------------------

answers
----------------------------------------------
id | question_id | description
----------------------------------------------
1  | 2           | Answers to the 2nd question
----------------------------------------------
2  | 1           | Answer for 1st question
----------------------------------------------
3  | 1           | Another answer for 1st
----------------------------------------------
现在,我想用用户(询问者)的名字、姓氏、用户名和问题的总答案数检索所有问题

请帮忙写。因为我把我的查询搞砸了,所以没有贴在这里


谢谢

当你可以将用户名作为主键时,为什么要使用用户id?你不是说一个问题的总答案数吗?@AurelioDeRosa:仅仅因为有一个记录
id
字段,它并不能将其作为主键,但通常有这个字段总是好的。想象一下,如果您将表的结构设置为具有活动日期,那么您可以具有相同的
用户名
(主键可以是用户名+日期字段),但记录
id
仍然是唯一的。在第一个表中,“fistname”当然应该是“firstname”。“编辑”功能不允许少于六个琐碎的更正,因此可能OP或主持人可以对单独的主键进行+1的更正@在这种情况下,OP可以在“username”上添加一个唯一的约束,但是有一个单独的整数PK是可以的。如果你有
q.*,u.*
你需要一个分组,而不仅仅是
q.id
。您必须通过
u.id、firstname、lastname、username、q.id、user\u id、title加入。
@vol7ron q.id是主键,为什么它对group by不够?@vol7ron:不在MySQL中。这是一个100%有效的(MySQL)查询,返回所询问的内容。(虽然我会使用:
用户留下的加入问题留下的加入答案
来显示没有提问的用户。)要求可能不是100%清楚,但我猜必须列出所有问题,即使没有用户回答。在此基础上,我认为您需要一些左连接,如@xdazz。所有问题都必须列出,但您的查询会给出多余的问题。是的,甚至没有用户回答。
SELECT q.*, u.*, COUNT(a.id) as answer_count
FROM questions q 
LEFT JOIN users u ON q.user_id = u.id
LEFT JOIN answers a ON a.question_id = q.id
GROUP BY q.id
select users.fistname,users.lastname,users.username 
from users, questions, answers
where users.id = questions.user_id and questions.id = answers.question_id