简体   繁体   中英

Select statement failing SQL Server

I have a select statement running in a jsp against SQL Server (previously using MySql without issues).

the TOP 1 was added because otherwise SQL Server moans about order by clauses (but only when displaying a result in a jsp, not when running the query inside SQL Server Management Studio).

This query runs fine in SQL Server Management Studio

SELECT TOP 1
alerts.id,
alerts.ts,
asset_firstname,
asset_lastname,
assetid,
alerttype.name,
node.zonename,
node.ipaddress,
node.zonegroupid
from
alerts, asset, alerttype, node, alertrules
where
ack=0 and
alerts.nodeid = node.id and
alerts.alerttypeid = alerttype.id and
alertrules.alerttypeid = alerts.alerttypeid and
alerts.assetid = asset.id and
alerts.alerttypeid = 1 and
asset.id=1157 and
alertrules.userid = 1
order by alerts.ts desc

but, when run in the jsp it returns "Column alerts.ts is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause".

I don't want alerts.ts aggregated or grouped by, hence the 'correct' select statement.

If I remove TOP 1 or alerts.ts desc the query returns the wrong row (earliest rather than latest record)

Converting what should be straightforward basic SQL commands so they run properly with SQL Server is proving a nightmare.

Any thoughts appreciated.

Regards Ralph

(I wrote this as an answer because as a comment would be a mess) You are using old style joins, and have redundant checks. Maybe this could make a difference (not sure, as it seems to be a problem related to JSP):

SELECT TOP(1)
  alerts.id, alerts.ts,
  asset_firstname,
  asset_lastname,
  assetid,
  alerttype.name,
  node.zonename,
  node.ipaddress,
  node.zonegroupid
from alerts
 inner join asset on alerts.assetid = asset.id 
 inner join alerttype on alerts.alerttypeid = alerttype.id
 inner join node on alerts.nodeid = node.id
 inner join alertrules on alertrules.alerttypeid = alerts.alerttypeid
where ack=0 and 
alerts.alerttypeid = 1 and
asset.id=1157 and
alertrules.userid = 1
order by alerts.ts desc; 

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