我的数据库看起来像这样
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=********;Database=*********;Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT p.cFName, p.cLName, s.cSugTitle, s.cEcrno, g.cName, h.mNotes, u.UserID, u.NetworkID FROM people p INNER JOIN suggest s ON p.cidPeople = s.cidPeople_WhoEntered INNER JOIN Grp g on s.cidGrp = g.cidGrp INNER JOIN history h ON h.cidSuggest = s.cidSuggest INNER JOIN users u ON u.cidPeople = p.cidPeople", conn);
SqlDataReader reader = cmd.ExecuteReader();
String path = @"C:\Users\AEEVANS\Desktop\example.csv";
using (StreamWriter sr = File.AppendText(path))
{
while (reader.Read())
{
sr.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.IsDBNull(5) ? null : reader.GetString(5), reader.GetString(6), reader.IsDBNull(7) ? null : reader.GetString(7));
sr.Close();
}
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
}
}
我正在尝试创建一个函数,该函数根据函数的输入参数选择行,并返回此行和下2行。
到目前为止,我所做的是该函数返回具有匹配参数的记录。
ID SSID BSSID RSSI
1. ABCD ab:cd:17 -68
2. efgh cd:as:25 -60
3. ijkl cs:gb:d6 -75
4. abcd dc:5g:f4 -72
....
518. ABCD ab:cd:17 -68
519. asfd ag:4g:32 -60
520. aasd gd:5g:56 -79
我要查找的结果是,例如,如果public Cursor getRequiredData(String mac, int level){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT BSSID, RSSI FROM Scans_table WHERE BSSID =? AND RSSI =?", new String[] {mac, String.valueOf(level)});
return res;
}
参数为mac
和ab:cd:17
,则该函数返回第1、2、3行(提供了示例数据)
编辑:
level = -68
此查询工作正常,但是它只给我第一条与Cursor res = db.rawQuery("SELECT * from Scans_table st where ID >= " +
"( select ID from Scans_table where BSSID =? AND RSSI =? ) order by st.ID asc limit 3 ", new String[] {mac, String.valueOf(level)});
和mac
参数匹配的记录,以及接下来的两条具有最高String.valueOf(level)
的记录。如果我的表有多个记录且这些参数的值相同怎么办?有没有办法获得所有匹配的记录和ID最高的2条下一条?(样本数据)
答案 0 :(得分:2)
假设“下一行”是指“具有次高ID的行”,则可以使用子查询来获取所需行的ID,然后使用order by
和limit
来获取接下来的两行:
select st.*
from scans_table st
where st.id >= (select st2.id from scans_table st2 where <your conditions are here>)
order by st.id asc
limit 3;