Question : Adding a Count() to a Union Query

Hi Folks,

I have an existing query that utilizes a UNION ALL to 'merge' 2 similar tables (allowing output by Date).  I have a 3rd table, 'comments', that contains data related to the previous 2 tables.

In simple terms, if you imagine this is for a blog, and there are 2 different types of entry (the 2 tables previously mentioned) and a combined comments table - that is effectively the setup.

I want to incorporate a comment count into the output (but not the comments themselves).  Is this possible?  The comments table contains the following fields;

ID, mid, c_name, c_email, c_comment & artid

artid is either the CodeID or DealID in the previously mentioned 2 tables.

My existing query is given below.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

SELECT 'CODE' AS TypeName, addeddate AS AddDate, thecode, mid, discount, discounttype, minspend, expiry_date, notes,  percentproduct, fixedproduct, NULL AS deal_detail, NULL AS deal_title, ID AS CodeID, NULL AS DealID
FROM discountcodes
WHERE mid='50'
UNION ALL
SELECT 'DEAL' AS TypeName, dateadded AS AddDate, NULL AS thecode, mid, NULL AS discount, NULL AS discounttype, NULL AS minspend, NULL AS expiry_date, NULL AS notes, NULL AS percentproduct, NULL AS fixedproduct, deal_detail, deal_title, NULL AS CodeID, ID AS DealID
FROM hotdeals
WHERE mid='50'
ORDER BY AddDate

Answer : Adding a Count() to a Union Query

ups... missed some brackets
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
SELECT 'CODE' AS TypeName, addeddate AS AddDate, thecode, mid, discount, discounttype, minspend, expiry_date, 
                notes,  percentproduct, fixedproduct, NULL AS deal_detail, NULL AS deal_title, ID AS CodeID, NULL AS DealID,
                (SELECT(COUNT(artid) FROM comment WHERE artid=ID) as COMMENTS
FROM discountcodes
WHERE mid='50'
UNION ALL
SELECT 'DEAL' AS TypeName, dateadded AS AddDate, NULL AS thecode, mid, NULL AS discount, NULL AS discounttype, 
NULL AS minspend, NULL AS expiry_date, NULL AS notes, NULL AS percentproduct, NULL AS fixedproduct, deal_detail, 
deal_title, NULL AS CodeID, ID AS DealID,
(SELECT(COUNT(artid) FROM comment WHERE artid=ID) as COMMENTS
FROM hotdeals
WHERE mid='50'
ORDER BY AddDate
Random Solutions  
 
programming4us programming4us