-2

I've got the following query which includes a left join which concatenates multiple tags. This query works.

  SELECT
    ap.userid, 
    ap.audioid,      
    u.id
       (
        SELECT GROUP_CONCAT(t.tagname)
        FROM entitytag et
        LEFT JOIN tags t on t.tagid = et.tagid
        WHERE et.audioid = ap.audioid
    ) tagname
FROM audioposts ap 
LEFT JOIN users u ON u.id = ap.userid

But now I'd like to add another left join which counts the number of replies to each ap.audioid from a table called replies. Anybody know how to add this extra left join?

Here's the query which works to count replies to a specified audioid from GET;

SELECT count('replyid') from replies WHERE opid = ?

But how do I add the extra left join to the first code so that I can fetch the reply count from the replies table for each audioid?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Meggy
  • 1,491
  • 3
  • 28
  • 63
  • 1
    I think there is as ',' missing after `u.id` ? – Luuk Aug 22 '20 at 17:48
  • 1
    Can you add some sample data + desired output? (in TEXT, no pictures) – Luuk Aug 22 '20 at 17:50
  • 1
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 22 '20 at 17:58

1 Answers1

1

no left join but reading your question this should work:

SELECT
    ap.userid, 
    ap.audioid,      
    u.id,
       (
        SELECT GROUP_CONCAT(t.tagname)
        FROM entitytag et
        LEFT JOIN tags t on t.tagid = et.tagid
        WHERE et.audioid = ap.audioid
    ) tagname,
    (
      select count('replyid') from replies WHERE opid = ap.audioid
    ) as count
FROM audioposts ap 
LEFT JOIN users u ON u.id = ap.userid
Luuk
  • 12,245
  • 5
  • 22
  • 33