结构:
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行,并且WHERE子句与所有与同一辆车相关的img_id中的最低img_id值。
我想要的结果:
|img_id(PK)| car_id| make | model | year | img_link |
-----------------------------------------------------------
| 1 | 1 | Toyot | Camry | 1999 | tcamry1.jpeg |
| 4 | 2 | Honda | Civic | 2005 | hcivic1.jpeg |
谢谢。
更新
我需要这些内容: - /
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 :(得分: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 希望这会有所帮助。
答案 1 :(得分: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
答案 2 :(得分:0)
SELECT *
FROM cars c
LEFT JOIN imgs g
ON c.car_id=g.car_id
WHERE 1
GROUP BY g.img_link;
尝试这个..但不确定。