0

I do a query in the following way:

SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
UNION
SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1;

With a correct output

docid   term    count
10398_txt_earn  100     1
10398_txt_earn  11340   1
10398_txt_earn  12  1
10398_txt_earn  1204    1
10398_txt_earn  198485  1
10398_txt_earn  20  1
10398_txt_earn  27  1
10398_txt_earn  28  1

And now I want to compute the number of rows in the result with the COUNT() operator but I don't know to apply it. Thanks in advance

Ubuntu14.04 SQLite with XAMPP

2 Answers 2

1

Are you looking for this?

select count(*)
FROM (SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
      UNION
      SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1
     ) t;

By the way, you can write your original query more efficiently as:

SELECT *
FROM frequency
WHERE count = 1 and (docid in  '10398_txt_earn', '925_txt_trade');

The count is then:

SELECT count(*)
FROM frequency
WHERE count = 1 and (docid in  '10398_txt_earn', '925_txt_trade');
Sign up to request clarification or add additional context in comments.

3 Comments

The t is a table alias. This is needed for subqueries in MySQL and necessary for certain join operations. In general, though, table aliases are useful to make queries easier to write and read.
Is something like a fake table or a temp table right?
@jd1215 . . . It is just a name for a table or subquery.
1

You can do:

SELECT COUNT(1)
FROM 
(
  SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
  UNION
  SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1
) a

Since you used a 'UNION', your results will remove duplicates. If you want to include all records (including any duplicates), then use a UNION ALL instead of a UNION.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.