結構:如何選擇2 tbls但從第二個tbl只有1行與MySQL中最低的PK?
TBL 1
|car_id(PK)| make | model | year |
-----------------------------------
| 1 | Toyot | Camry | 1999 |
| 2 | Honda | Civic | 2005 |
TBL 2
|img_id(PK)| car_id| img_link |
------------------------------------
| 1 | 1 | tcamry1.jpeg |
| 2 | 1 | tcamry2.jpeg |
| 3 | 1 | tcamry3.jpeg |
| 4 | 2 | hcivic1.jpeg |
| 5 | 2 | hcivic2.jpeg |
我的查詢:
SELECT *
FROM cars c
LEFT JOIN imgs g
ON c.car_id=g.car_id
WHERE 1
結果:
|img_id(PK)| car_id| make | model | year | img_link |
-----------------------------------------------------------
| 1 | 1 | Toyot | Camry | 1999 | tcamry1.jpeg |
| 2 | 1 | Toyot | Camry | 1999 | tcamry2.jpeg |
| 3 | 1 | Toyot | Camry | 1999 | tcamry3.jpeg |
| 4 | 2 | Honda | Civic | 2005 | hcivic1.jpeg |
| 5 | 2 | Honda | Civic | 2005 | hcivic2.jpeg |
我需要爲每輛車獲取1行,並且在與同一輛車相關的所有img_id中包含類似最低img_id值的WHERE子句。
結果我想:
|img_id(PK)| car_id| make | model | year | img_link |
-----------------------------------------------------------
| 1 | 1 | Toyot | Camry | 1999 | tcamry1.jpeg |
| 4 | 2 | Honda | Civic | 2005 | hcivic1.jpeg |
謝謝。
UPDATE:
我需要的東西沿着這些路線: -/
SELECT g.id, c.car_id, c.mc_make, c.mc_model, c.mc_year, c.mc_desc
FROM mycars c
INNER JOIN (SELECT * FROM mycars_gallery g WHERE)
ON c.car_id=g.car_id
WHERE g.id = min(g.id)
我有一種感覺,我需要看min()函數,參見上面的更新。我只是不知道正確的語法 – Tatarin