好的,这是设置:
mysql> create table VEHICLES ( ID INT PRIMARY KEY, VIN CHAR( 17 ) );
mysql> INSERT INTO VEHICLES ( ID, VIN ) VALUES( 1, '12341234123412341' );
mysql> INSERT INTO VEHICLES ( ID, VIN ) VALUES( 2, '23452345234523452' );
mysql> INSERT INTO VEHICLES ( ID, VIN ) VALUES( 3, '34534534534534534' );
注意我必须在 IMAGES 表中将该列重命名DEFAULT
为DEF
:
mysql> CREATE TABLE IMAGES ( ID INT PRIMARY KEY, VEHICLEID INT, NAME VARCHAR(20), DEF INT );
mysql> INSERT INTO IMAGES( ID, VEHICLEID, NAME, DEF ) VALUES( 1, 1, 'a', 1 );
mysql> INSERT INTO IMAGES( ID, VEHICLEID, NAME, DEF ) VALUES( 2, 1, 'b', 0 );
mysql> INSERT INTO IMAGES( ID, VEHICLEID, NAME, DEF ) VALUES( 3, 2, 'c', 0 );
mysql> INSERT INTO IMAGES( ID, VEHICLEID, NAME, DEF ) VALUES( 4, 2, 'd', 0 );
这就是解决方案。
首先,我们需要一个查询,每辆车获取一个图像行,如果有则选择默认行。
我们通过按 DEF 的降序对图像进行排序(因此 1 位于顶部),然后进行分组VEHICLEID
以确保每辆车只有一行。
mysql> SELECT * FROM ( SELECT * FROM IMAGES ORDER BY DEF DESC ) sortedimages GROUP BY VEHICLEID;
+----+-----------+------+------+
| ID | VEHICLEID | NAME | DEF |
+----+-----------+------+------+
| 1 | 1 | a | 1 |
| 3 | 2 | c | 0 |
+----+-----------+------+------+
现在我们从VEHICLES
表中选择,并选择LEFT OUTER JOIN
上面的查询,以确保我们总是每辆车得到一行:
mysql> SELECT * FROM VEHICLES LEFT OUTER JOIN ( SELECT * FROM ( SELECT * FROM IMAGES ORDER BY DEF DESC ) sortedimages GROUP BY VEHICLEID ) defaultimages ON VEHICLES.ID = defaultimages.VEHICLEID;
+----+-------------------+------+-----------+------+------+
| ID | VIN | ID | VEHICLEID | NAME | DEF |
+----+-------------------+------+-----------+------+------+
| 1 | 12341234123412341 | 1 | 1 | a | 1 |
| 2 | 23452345234523452 | 3 | 2 | c | 0 |
| 3 | 34534534534534534 | NULL | NULL | NULL | NULL |
+----+-------------------+------+-----------+------+------+