-1

create a sql query to display the last 5 records of the Sdelki table by Users.ID_user the Users table is linked to the Clients table by ID_User, and the Klients table is linked to the Sdelki table by ID_Klient

this query didn't work

SELECT Sdelki.*
FROM Sdelki
INNER JOIN Klients
ON Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN Users
ON Klients.ID_user = Users.ID_user
ORDER BY Sdelki.ID_sdelki DESC
LIMIT 5;

using SQL Server

jarlh
  • 42,561
  • 8
  • 45
  • 63
  • 1
    What was wrong with the results produced by this query? – FrustratedWithFormsDesigner Jun 21 '23 at 12:53
  • 3
    What do you mean by "this query didn't work"? – Dai Jun 21 '23 at 12:53
  • ...and how is "last N records" defined in your table? Contrary to what many people assume, RDBMS like SQL Server don't actually keep track of record insertion order or track other metadata (Sqlite is the exception): so you can only do that if you have an `IDENTITY` column that is _never_ reset, or you have a `Created datetime2` column which is _never_ arbitrarily overwritten. – Dai Jun 21 '23 at 12:56
  • SQL Server has TOP, or FETCH FIRST, instead of LIMIT. – jarlh Jun 21 '23 at 13:04

2 Answers2

0

You need to use Klients.ID_user or Users.ID_user in order by clause to get the expected results.

SELECT
    TOP 5 Sdelki.*
FROM 
    Sdelki
INNER JOIN 
    Klients
ON 
    Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN 
    Users
ON 
    Klients.ID_user = Users.ID_user
ORDER BY 
    Klients.ID_user DESC;

This is the updated query

EDIT: removed LIMIT 5 and used TOP 5 in the query, since LIMIT isn't supported in SQL Server.

Zero
  • 1,807
  • 1
  • 6
  • 17
0

Sql Server doesn't use LIMIT, it uses TOP instead :

SELECT TOP (5) Sdelki.*
FROM Sdelki
INNER JOIN Klients
ON Sdelki.ID_Klient = Klients.ID_Klient
INNER JOIN Users
ON Klients.ID_user = Users.ID_user
ORDER BY Sdelki.ID_sdelki DESC
SelVazi
  • 10,028
  • 2
  • 13
  • 29