Question

I have the following query:

string Query = String.Format("SELECT ArticleName FROM tblArticles WHERE UserID={0} ORDER BY PostDate DESC", UserID);

I want to get not more than 3 different values for the 'ArticleName'.
Is it possible to do that? (without select all the 'ArticleName' just 3 of them?)

Thanks.

Was it helpful?

Solution 2

Typically you can use LIMIT 3 at the end of the query to achieve this

string Query = String.Format(
    "SELECT ArticleName FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC LIMIT 3",
    UserID
);

Or for Microsoft Access DB apparently you need to use TOP 3 at the start instead, eg:

string Query = String.Format(
    "SELECT TOP 3 ArticleName FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC",
    UserID
);

OTHER TIPS

You need to say what RDBMS are you using. Mysql and sqlite support the LIMIT directive while other systems may or may not support TOP, FIRST or other similar directives.

UPDATE: Look at how different RDBMS engines support that. See getLoadSomeRowsSql() method in infinispan's TableManipulation.java.

Here it is, in case the link stops working:

 switch (getDatabaseType()) {
    case ORACLE:
       loadSomeRowsSql = String.format("SELECT %s, %s FROM (SELECT %s, %s FROM %s) WHERE ROWNUM <= ?", dataColumnName, idColumnName, dataColumnName, idColumnName, getTableName());
       break;
    case DB2:
    case DB2_390:
    case DERBY:
       loadSomeRowsSql = String.format("SELECT %s, %s FROM %s FETCH FIRST ? ROWS ONLY", dataColumnName, idColumnName, getTableName());
       break;
    case INFORMIX:
    case INTERBASE:
    case FIREBIRD:
       loadSomeRowsSql = String.format("SELECT FIRST ? %s, %s FROM %s", dataColumnName, idColumnName, getTableName());
       break;
    case SQL_SERVER:
       loadSomeRowsSql = String.format("SELECT TOP (?) %s, %s FROM %s", dataColumnName, idColumnName, getTableName());
       break;
    case ACCESS:
    case HSQL:
    case SYBASE:
       loadSomeRowsSql = String.format("SELECT TOP ? %s, %s FROM %s", dataColumnName, idColumnName, getTableName());
       break;
    default:
       // the MySQL-style LIMIT clause (works for PostgreSQL too)
       loadSomeRowsSql = String.format("SELECT %s, %s FROM %s LIMIT ?", dataColumnName, idColumnName, getTableName());
       break;
 }

Maybe

SELECT DISTINCT TOP 3 ArticleName, PostDate FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC

Use this:

string Query = String.Format("SELECT DISTINCT TOP 3 ArticleName FROM tblArticles WHERE UserID={0} ORDER BY PostDate DESC", UserID);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top