我正在尝试使用子查询从子表中获得前1个结果。当我尝试使用子查询orderby or OrderByDescending
时,它会抛出
的NullReferenceException
。不使用orderby or OrderByDescending
我的查询执行成功。
但我想获得子查询的最后记录。我的应用程序与Mysql数据库连接。
我的代码在下面给出
var result = (from ud in db.user_devices
join a in db.access_info on ud.u_id equals a.u_id
join d in db.device_num on ud.dev_id equals d.DevId
//let pi = db.packet_info.Where(x => x.DevId == ud.dev_id && x.DevId != null).OrderByDescending(x =>x.systime).FirstOrDefault()
//where pi != null
select new
{
fuel = db.packet_info.Where(x => x.DevId == ud.dev_id).OrderByDescending(x => x.systime).Select(x => x.fuel).FirstOrDefault(),
//removed other fields
}).ToList();
答案 0 :(得分:0)
使用另一种方法,创建一个与linq具有相同模式的过程。
程序代码如下:
CREATE DEFINER=`abc`@`%` PROCEDURE `spGetAllVechiles`()
BEGIN
SELECT
(SELECT g.fuel FROM abc.Packet_Info AS g WHERE g.devid = ud.dev_id order by systime desc LIMIT 0,1 ) AS fuel,
(SELECT g.fencealarm FROM abc.Packet_Info AS g WHERE g.devid = ud.dev_id order by systime desc LIMIT 0,1 ) AS fencealarm,
(SELECT g.speed FROM abc.Packet_Info AS g WHERE g.devid = ud.dev_id order by systime desc LIMIT 0,1 ) AS speed,
(SELECT g.Latitude FROM abc.Packet_Info AS g WHERE g.devid = ud.dev_id order by systime desc LIMIT 0,1 ) AS Latitude,
(SELECT g.Longitude FROM abc.Packet_Info AS g WHERE g.devid = ud.dev_id order by systime desc LIMIT 0,1 ) AS Longitude
//other params...
FROM abc.access_info AS ac
INNER JOIN abc.user_devices AS ud ON ud.u_id = ac.u_id
INNER JOIN abc.device_num AS dn ON dn.DevId = ud.dev_id;