Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL - LEFT JOIN value of columnX where MAX(columnY)
    primarykey
    data
    text
    <p>So this is my query:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wagons.id, wagons.mid, wagons.year, wagons.make, wagons.model, wagons.nickname, wagons.description, members.first, members.last, wagon_photos.filename, Count(DISTINCT( likes.id )) AS likes, Count(DISTINCT( comments.id )) AS comments FROM wagons INNER JOIN members ON members.mid = wagons.mid LEFT JOIN wagon_photos ON wagon_photos.wid = wagons.id LEFT JOIN likes ON likes.wid = wagons.id LEFT JOIN comments ON comments.wid = wagons.id GROUP BY wagons.id ORDER BY wagons.id DESC LIMIT 10 </code></pre> <p>I am trying to fetch the <code>wagon_photos.filename</code> where <code>wagon_photos.default</code> is the maximum value. (It's a boolean, where only one row <em>(for each <code>wagon_photos.wid</code>)</em> will be 1.) On the off-chance the member does not have a default photo selected, I'd like it to return the lowest <code>wagon_photos.id</code> if possible.</p> <p>I have tried numerous queries with ORDER BY and GROUP BY, but I think it may be a little more complicated than that. If I use a WHERE clause, it left out any wagons that did not have any photos linked to it, which I do not want to do.</p> <hr> <pre><code>CREATE TABLE `wagons` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `mid` int(8) DEFAULT NULL, `year` varchar(4) DEFAULT NULL, `make` varchar(50) DEFAULT NULL, `model` varchar(100) DEFAULT NULL, `nickname` varchar(200) DEFAULT NULL, `description` mediumtext, `featured` int(1) DEFAULT '0', `visibility` int(1) DEFAULT '1', `commision` int(1) DEFAULT '1', `feat1title` varchar(50) DEFAULT NULL, `feat2title` varchar(50) DEFAULT NULL, `feat3title` varchar(50) DEFAULT NULL, `feat4title` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=617 DEFAULT CHARSET=utf8; CREATE TABLE `wagon_photos` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `wid` int(11) DEFAULT NULL, `filename` varchar(255) DEFAULT NULL, `caption` varchar(255) DEFAULT '', `default` int(1) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload