Heim > Fragen und Antworten > Hauptteil
Vereinfachtes Beispiel:
select ticket_id, `number` as 'ticket number', (SELECT count(*) from ost_thread_entry join ost_thread on ost_thread_entry.thread_id = ost_thread.id where ost_thread.object_id = 1234) as 'number of posts in ticket' from ost_ticket
Ich muss den Wert in ticket_id
angeben, nicht in 1234
P粉7412238802024-02-05 00:17:41
您可以在此处使用表别名:
SELECT ticket_id, number AS `ticket number`, (SELECT COUNT(*) FROM ost_thread_entry ote INNER JOIN ost_thread ot ON ote.thread_id = ot.id WHERE ot.object_id = t.ticket_id) AS `number of posts in ticket` FROM ost_ticket t;
请注意,您也可以在不使用相关子查询的情况下编写查询,而是使用联接:
SELECT t.ticket_id, t.number AS `ticket number`, COUNT(ote.thread_id) AS `number of posts in ticket` FROM ost_ticket t LEFT JOIN ost_thread ot ON ot.object_id = t.ticket_id LEFT JOIN ost_thread_entry ote ON ote.thread_id = ot.id GROUP BY t.ticket_id, t.number;