简体   繁体   中英

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. 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".

Now i would like to get and count for each entry all questions as a single value. 条目,并为每个条目将所有问题计数为一个值。
:

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:

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'

I tried to inner join them with "on" like:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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