我有一个名为rendeles_termekek的表。(英文,ordered_products)
我想算一下,每件产品的订购次数。
使用下面的SQL,我得到4作为ennyi。我上传了一张图片,并为每行写了正确的数字。
SELECT DISTINCT
rendeles_termekek.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek ) AS ennyi
FROM rendeles_termekek
LEFT JOIN termek ON rendeles_termekek.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC
答案 0 :(得分:0)
我认为你的表中只有四行" rendeles_termekek"。
我已更新您的查询。试试这个
SELECT DISTINCT
rendeles_termekek.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi
FROM rendeles_termekek r1
LEFT JOIN termek ON rendeles_termekek.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC
请注意,我更改了子查询并在其中添加了where条件
`( SELECT COUNT(rendeles_termekek.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi`
答案 1 :(得分:0)
**r1** is the alias of your table rendeles_termekek so you have to access those columns through alias name "r1" like I did in below query. try below
SELECT DISTINCT
r1.termek_id,
termek.termek_id,
termek.termek_nev,
( SELECT COUNT(r.termek_id) FROM rendeles_termekek r where r.termek_id = r1.termek_id ) AS ennyi
FROM rendeles_termekek r1
LEFT JOIN termek ON r1.termek_id = termek.termek_id
ORDER BY termek.termek_nev ASC