[英]Count all rows from a second table connected by id and add the value on the right row of the first table
I have 2 tables, in one table i save entrys. 我有2张桌子,我在一张桌子中保存条目。 Like for example a entry where i offer a smartphone. 例如,例如我提供智能手机的条目。
On each entry there can be more questions. 在每个条目上可能会有更多问题。 Like for example a chat for customer and supplier. 例如,针对客户和供应商的聊天。
This question get saved in a second table. 该问题将保存在第二个表中。 Each question will get the "entry id". 每个问题都将获得“条目ID”。
Now i would like to get all entrys and count for each entry all questions as a single value. 现在,我想获取所有条目,并为每个条目将所有问题计数为一个值。
For example : 例如 :
id |title | desc | questionscount
1 |samsung s7.. | smartphone bla bla | 11
2 |samsung s6.. | bla bla bla | 5
3 |samsung s5.. | bla bla | 0
I simplified my sql and i think im really close: 我简化了我的SQL,我认为我真的很接近:
SELECT
e.id, e.uid, e.tmstmp, e.title, e.desc, questioncount
FROM
entrys e
INNER JOIN
(
SELECT eid, COUNT(id) as questioncount
FROM question
WHERE eid = e.id
) q
->Unknown column 'e.id' in 'where clause' ->“ where子句”中的未知列“ e.id”
I tried to inner join them with "on" like: 我试图通过“ on”内部加入它们,例如:
ON q.eid = e.id
but like that not all rows are selected and questioncount get the value from all question no matter if eid = e.id. 但是,即使eid = e.id,也并非所有行都被选中,并且问题计数从所有问题中获取值。
Use left join so it will return all rows from entrys whether each entry has a question or not. 使用左联接,因此无论每个条目是否有问题,它都会返回条目中的所有行。
SELECT
e.id, e.uid, e.tmstmp, e.title, e.desc, COUNT(q.id) questioncount
FROM
entrys e
LEFT JOIN question q on e.id = q.eid
GROUP BY e.id
Select the count as a subquery 选择计数作为子查询
SELECT e.id, e.uid, e.tmstmp, e.title, e.desc,
(SELECT COUNT(q.id) FROM question q WHERE q.eid = e.id) AS questioncount
FROM entrys e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.