我正在尝试在下面的查询中添加表t4的计数,而不限制结果。 类似的东西:
COUNT(t4.offer_to_purchase_id) AS count
但这会将结果限制为仅显示在t4中的那些服务,尽管有左连接
$sql = "SELECT s.*, q.categories, t4.*, payments.*, quotes.*
FROM services s
LEFT JOIN
(
SELECT sc.service_id, GROUP_CONCAT(c.name) categories
FROM services_categories sc JOIN categories c
ON sc.cat_id= c.cat_id
GROUP BY sc.service_id
) q ON s.service_id = q.service_id
LEFT JOIN offers_to_purchase t4
ON s.service_id = t4.service_id
LEFT JOIN quotes ON quotes.service_id = s.service_id
LEFT JOIN payments ON payments.service_id = s.service_id
WHERE s.user_id = $user_id";
我怎样才能做到这一点?
答案 0 :(得分:2)
它应该工作(因为它将计算非空值),但不确定如何对记录进行分组以获取它,看到你似乎正在返回该表中的所有记录。
如果你想要一个可以用于所有行的计数,同时从t4带回行,你可以这样做: -
$sql = "SELECT s.*, q.categories, t4.*, payments.*, quotes.*, t4_2.id_count
FROM services s
LEFT JOIN
(
SELECT sc.service_id, GROUP_CONCAT(c.name) categories
FROM services_categories sc JOIN categories c
ON sc.cat_id= c.cat_id
GROUP BY sc.service_id
) q ON s.service_id = q.service_id
LEFT JOIN offers_to_purchase t4
ON s.service_id = t4.service_id
LEFT OUTER JOIN
(
SELECT service_id, COUNT(offer_to_purchase_id) AS id_count FROM offers_to_purchase GROUP BY service_id
) t4_2
ON s.service_id = t4_2.service_id
LEFT JOIN quotes ON quotes.service_id = s.service_id
LEFT JOIN payments ON payments.service_id = s.service_id
WHERE s.user_id = $user_id";