我有以下查询:
string Query = String.Format("SELECT ArticleName FROM tblArticles WHERE UserID={0} ORDER BY PostDate DESC", UserID);
我想为' ArticleName'获得不超过3个不同的值 有可能吗? (没有选择所有' ArticleName'只有3个?)
感谢。
答案 0 :(得分:3)
您需要说明您使用的是哪种RDBMS。 Mysql和sqlite支持LIMIT
指令,而其他系统可能支持也可能不支持TOP
,FIRST
或其他类似指令。
更新:看看不同的RDBMS引擎如何支持它。请参阅infinispan的TableManipulation.java
中的getLoadSomeRowsSql()
方法。
如果链接停止工作,就在这里:
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;
}
答案 1 :(得分:2)
通常,您可以在查询结尾使用LIMIT 3
来实现此目标
string Query = String.Format(
"SELECT ArticleName FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC LIMIT 3",
UserID
);
或者对于Microsoft Access DB,显然您需要在开始时使用TOP 3
,例如:
string Query = String.Format(
"SELECT TOP 3 ArticleName FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC",
UserID
);
答案 2 :(得分:1)
也许
SELECT DISTINCT TOP 3 ArticleName, PostDate FROM tblArticleas WHERE UserID={0} ORDER BY PostDate DESC
答案 3 :(得分:1)
使用此:
string Query = String.Format("SELECT DISTINCT TOP 3 ArticleName FROM tblArticles WHERE UserID={0} ORDER BY PostDate DESC", UserID);