Jump to content

Recommended Posts

I got a problem when I do a count from two tables and when I have an UNION between them. MY select looks like this:

SELECT DISTINCT COUNT(ID) AS n FROM Table1 WHERE age = 10 UNION
SELECT COUNT(ID) AS n FROM Table2 WHERE age = 10

This give me a table with two rows.

But what I want is one row which has counted this two tables and sorted out all dubletts so I only get the DISTINCT values.. ??? ::)

It depends on which database version you are using, but try this:

 

SELECT count(*) FROM (select id from Table1 where age = 10 UNION select id from Table2 where age = 10)

 

It might ask you to give an alias for the subquery.. if so, add "AS foo" at the end of the query.  Or it may give an error if you are using mysql version 4.

 

There is no need to use distinct, as UNION already does that.  If you don't want distinct values you should use UNION ALL instead.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.