0

Is there a way to create a query to select only the first result that's compatible for both MySQL and SQL Server?

SELECT TOP 1 mycolumn, mycolumn2
FROM mytable
ORDER BY ID DESC

works for SQL Server.

but

SELECT mycolumn, mycolumn2
FROM mytable
ORDER BY ID DESC
LIMIT 1

works only for MySQL.

I'm not looking to download any PDO or database abstraction class - I'm wondering if there are SQL queries compatibility to both?

tester2001
  • 1,053
  • 3
  • 14
  • 24

2 Answers2

0

Is there a way to create a query to select only the first result that's compatible for both MySQL and SQL Server?

Short answer, no.

Long answer, not in any way efficiently. Somebody else suggested WHERE id = MAX(id). That will work if id is the primary key. But not with the kind of optimization that the TOP and/or LIMIT features provide.

Sorry.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
0

If you want to get TOP 1, you can use max() -- DESC or min() -- ASC. But if you want get TOP N, you can try something like this:

SELECT mycolumn, mycolumn2
FROM mytable M1
WHERE (SELECT COUNT(*)
       FROM mytable M2
       WHERE M1.ID < M2.ID) < N  -- M1.ID < M2.ID: DESC, < N: TOP N
Nguyễn Hải Triều
  • 1,454
  • 1
  • 8
  • 14