简体   繁体   中英

Get count and result from SQL query in Go

I'm running a pretty straightforward query using the database/sql and lib/pq (postgres) packages and I want to toss the results of some of the fields into a slice, but I need to know how big to make the slice.

The only solution I can find is to do another query that is just SELECT COUNT(*) FROM tableName; .

Is there a way to both get the result of the query AND the count of returned rows in one query?

Conceptually, the problem is that the database cursor may not be enumerated to the end so the database does not really know how many records you will get before you actually read all of them. The only way to count (in general case) is to go through all the records in the resultset.

But practically, you can enforce it to do so by using subqueries like

select *, (select count(*) from table) from table

and just ignore the second column for records other than first. But it is very rude and I do not recommend doing so.

Not sure if this is what you are asking for but you can call the @@Rowcount function to return the count of the previous select statement that has been executed.

SELECT mytable.mycol FROM mytable WHERE mytable.foo = 'bar'

SELECT @@Rowcount

If you want the row count included in your result set you can use the the OVER clause ( MSDN )

SELECT mytable.mycol, count(*) OVER(PARTITION BY mytable.foo) AS 'Count' FROM mytable WHERE mytable.foo = 'bar'

You could also perhaps just separate two SQL statements with the a ; . This would return a result set of both statements executed.

You would used count(*)

SELECT count(distinct last)
FROM (XYZTable)
WHERE date(FROM_UNIXTIME(time)) >= '2013-10-28' AND
id = 90 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM