1

structure:

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 |

My query:

SELECT *
FROM cars c
LEFT JOIN imgs g
ON c.car_id=g.car_id
WHERE 1

Result:

|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 |

I need to get 1 row for each car and have WHERE clause with something like lowest img_id value out of all img_id related to the same car.

Result I want:

|img_id(PK)| car_id| make  | model | year |   img_link    |
-----------------------------------------------------------
|     1    |    1  | Toyot | Camry | 1999 |  tcamry1.jpeg |
|     4    |    2  | Honda | Civic | 2005 |  hcivic1.jpeg |

Thank you.

UPDATE:

I need something along these lines :-/

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)
4

3 回答 3

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 希望这会有所帮助。

于 2013-08-30T15:21:03.333 回答
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
于 2013-08-30T15:18:01.800 回答
0
SELECT *
FROM cars c
LEFT JOIN imgs g
ON c.car_id=g.car_id
WHERE 1
GROUP BY g.img_link;

试试这个..虽然不确定。

于 2013-08-30T15:09:50.343 回答