2013-08-30 50 views
1

結構:如何選擇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) 
+0

我有一種感覺,我需要看min()函數,參見上面的更新。我只是不知道正確的語法 – Tatarin

回答

2

嘗試:

SELECT MIN(b.img_id), a.car_id, a.make, a.model, a.year, b.img_link 
FROM cars a 
LEFT JOIN imgs b ON a.car_id = b.car_id 
GROUP BY a.car_id, a.make, a.model, a.year ; 

演示:http://sqlfiddle.com/#!2/1469f/15 希望這有助於。

+0

謝謝,它的工作原理! – Tatarin

0
SELECT * 
FROM cars c 
LEFT JOIN imgs g 
ON c.car_id=g.car_id 
WHERE 1 
GROUP BY g.img_link; 

試試這個..不知道,但。

+0

仍然是相同的結果。沒有工作 – Tatarin

1
SELECT * 
FROM cars c 
LEFT JOIN imgs g 
ON c.car_id=g.car_id 
WHERE img_id IN(SELECT MIN(img_id)) GROUP BY model 
相關問題