Question

STEP 1

Select data1,name,phone,address from dummyTable limit 4;

From above query, I will get the following result for example:

 data1 | name | phone | address

 fgh   | hjk  | 567...| CA 
 ghjkk | jkjii| 555...| NY

Now, after having the above result I am suppose to match data1 records that I got from above query to existing another table in a database called existingTable which has a same column called data1 in it. If the result above gives data1 value as 'fgh' so I take that 'fgh' and compare with that existingtable column called data1.

STEP 2

Next, after I am finished comparing, I need to apply some condition as follows:

if((results.data1.value).equals(existingTable.data1.value))
then count --
else
count++

So by above condition I am trying to explain, that if the value I got from the result is matched then I do count decrement by 1 and if not then count is incremented by 1.

Summary I basically wanted to achieve this in one single query, is it possible using PostgreSQL?

No correct solution

OTHER TIPS

I think you can translate that to a simple query:

SELECT d.data1, d.name, d.phone, d.address
     , count(*) - 2 * count(e.data1)
FROM  (
   SELECT data1, name, phone, address
   FROM   dummytable
   -- ORDER BY ???
   LIMIT  4
   ) d
LEFT   JOIN existingtable e USING (data1)
GROUP  BY d.data1, d.name, d.phone, d.address;

The major ingredient is the LEFT [OUTER] JOIN. Follow the link to the manual.

count(*) counts all rows from dummytable.
count(e.data1) only counts rows from existingtable where a matching data1 exists (count() does not count NULL values). I subtract that twice to match your formula.

About ORDER BY: There is no natural order in a database table. You need to order by something to get predictable results.

If there can be duplicates in existingtable but you want to count every distinct data1 only once, eliminate dupes before you join or use an EXISTS semi-join:

SELECT data1, name, phone, address
      , count(*) - 2 * count(EXISTS (
                          SELECT 1 FROM existingtable e
                          WHERE  e.data1 = d.data1) OR NULL)
FROM  (
   SELECT data1, name, phone, address
   FROM   dummytable
   -- ORDER BY ???
   LIMIT  4
   ) d
GROUP BY data1, name, phone, address;

The last count works because (TRUE OR NULL) IS TRUE, but (FALSE OR NULL) IS NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top