question

imrankasuri avatar image
imrankasuri asked

Issue in Making the query from another table

Dear Sir, I have the following table structure ![alt text][1] [1]: /storage/temp/574-image1.jpg i need tblCarPurchase.ID and tblCarImages.ID as Image_Id but the id required from this table should be according to the SortOrder column in tblcarimages table. for example there are three records in the table tblcarimages but i need only one based on the lower sort order, if the second record has sort order 1, it will be come with the ID of the main Table. Thanks in Advance.
viewsub-queryrelationships
image1.jpg (209.0 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Grant Fritchey avatar image
Grant Fritchey answered
I don't completely understand. Values in SortOrder will eliminate rows? If you mean that you have multiple values in the tblCarImages table and you want only one of those returned, then something like this: SELECT cp.ID, dt.Image_ID FROM dbo.tblCarPurchase AS cp CROSS APPLY (SELECT TOP(1) ci.ID AS Image_ID FROM dbo.tblCarImages AS ci WHERE ci.Car_ID = cp.ID ORDER BY ci.SortOrder DESC) AS dt That will return a single value, ordered by the SortOrder for each column in the tblCarPurchase table. Just a couple of points on the side. If you're designing these tables, I would strongly recommend you reexamine your naming conventions. tbl as a marker for tables is just confusing and extra letters. The whole concept of what's called Hungarian notation has fallen out of favor in code, let alone in databases. Also, having a table called CarPurchase with an identity column called ID and then a foriegn key column called CarID is extremely confusing. It's going to make maintaining that code over time incredibly hard. If the name you're going to refer to it as is CarID, then name it that in the main table.
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.