Question

I'm trying to do something in my new Webmatrix site, and I'm not sure it is possible.

I have the following 2 tables in my database.

Property PropertyID, PropertyName, Primary_Image

Images PropertyID, ImageURL, ImageID

I have set up a page for each property, which shows ALL images that belong to that property. The problem is, I want to order those images, so that the primary image shows at the top? How can I make that happen?

Here's my current SQL query:

var images = db.query("SELECT * FROM Images JOIN Property ON Images.ImageID=Property.Primary_Image WHERE PropertyID = @0"), PropertyID;
Was it helpful?

Solution

Try with:

var images = db.query(@"SELECT t1.* FROM Images t1 LEFT JOIN Property t2 ON
    t1.ImageID = t2.Primary_Image WHERE t1.PropertyID = @0 ORDER BY
    t2.Primary_Image DESC", PropertyID);

With this query you filter the records from Images that have a given PropertyID joining with the matching rows of Property.
Since only the primary image has a matching row in Property, this record is the only that has a value in Primary_Image: ordering in descending order puts this record at the first place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top