尝试将COUNT查询合并到现有的SELECT查询中

时间:2013-09-11 08:51:58

标签: mysql sql

我试图将COUNT查询合并到我现有的SELECT查询中。

目前,我使用此SELECT语句来获取一些联系信息:

SELECT contact.id_contact, contact.cname, contact.cemail, contact.trading_id, trading_name.trading_name
FROM contact
INNER JOIN trading_name ON contact.trading_id = trading_name.id_trading_name
WHERE (CHAR_LENGTH(contact.cname) > 0)
ORDER BY contact.cname

我也有这个COUNT查询,我需要以某种方式包含在同一个SELECT语句中:

SELECT COUNT(AlertID) AS CustomerAlertCountTotal FROM customer_support_dev.customer_alerts WHERE (AlertTradingID = @tradingid)

基本上我需要知道每个'trading_name'有多少'AlertID',并且要在'CustomerAlertCountTotal'中返回该值 - 但是只使用一个查询。

(如果它有所不同,我使用的是MySQL数据库)

希望有道理:)

2 个答案:

答案 0 :(得分:0)

SELECT contact.id_contact, contact.cname, contact.cemail, 
contact.trading_id, trading_name.trading_name,CustomerAlertCountTotal
FROM contact
INNER JOIN trading_name 
ON contact.trading_id = trading_name.id_trading_name
LEFT JOIN (SELECT COUNT(AlertID) AS CustomerAlertCountTotal,AlertTradingID 
FROM customer_support_dev.customer_alerts )as count
on count.AlertTradingID=contact.trading_id
WHERE (CHAR_LENGTH(contact.cname) > 0)
ORDER BY contact.cname

答案 1 :(得分:0)

只是我的预感。如果您与联系人和客户联系。你可以合并这样的东西。如果需要调整,请告诉我。

    SELECT contact.id_contact, contact.cname, contact.cemail, contact.trading_id, trading_name.trading_name, count(AlertID)
    FROM contact
    INNER JOIN trading_name 
     ON contact.trading_id = trading_name.id_trading_name
    LEFT JOIN customer_alerts
     ON contact.id = costumer_alerts.contact_id
    WHERE
     (CHAR_LENGTH(contact.cname) > 0) AND
     AlertTradingID = @tradingid
    GROUP BY contact.id
    ORDER BY contact.cname