2012-11-07 121 views
1

table1的LEFT JOIN 2表,但只从表2返回第1记录

cid 
itemdesc 
itemprice 

表2

cid 
imagename 
status 

我的第一个表是具有独特的CID(不重复),我希望它LEFT JOIN TO table2但它有多个行每个cid

cid  imagename   status 
1  image1-of-cid1  test1 
1  image2-of-cid1  test2 
2  image1-of-cid2  test3 
2  image2-of-cid2  test4 
2  image3-of-cid2  test5 

但我只想要查询返回第一行只有每个r FOM的eCord表1

感谢

回答

1

你需要创建一个额外的子查询得到每一个cidimagename。试试这个,

SELECT a.*, b.* 
FROM table1 a 
     LEFT JOIN 
     (
      SELECT cid, MIN(imagename) minImage 
      FROM table2 
      GROUP BY cid 
     ) c ON a.cid = c.cid 
     LEFT JOIN table2 b 
      ON c.cid = b.cid AND 
       b.imageName = c.minImage 
+0

任何特别的原因,为什么要建立这样一个复杂的查询,以及为什么它的更好比我提供的? (我真的对你的理由感兴趣,而不仅仅是拖动) – Vyktor

+0

@Vyktor,因为在你的代码中,你的group by子句中只包含*非聚合*列,并且没有列被聚合到你的select子句上。这会给你无效的结果。请稍等,我会给你演示。感谢您顺便问一下。 –

+0

嗯,我的解决方案[给我同样的结果](http://sqlfiddle.com/#!2/15188/11/0)你有任何示例/源显示它有什么问题吗? – Vyktor

0
Select 
    distinct a.cid,a.itemdesc,b.imagename,a.itemprice,b.status 
from table1 a, 
table2 b 
where a.cid=b.cid 
2

我同意上述吴宇森的回答。你需要某种类型的子查询到实际检索表的第一行2,喜欢的东西:

SELECT 
t1.[id], 
t2.* 
FROM table1 AS t1 
LEFT JOIN table2 AS t2 
    ON t2.cid = (SELECT TOP 1 cid FROM table2 WHERE cid = t1.cid) 
0

试试这个:

SELECT a.cid, a.itemdesc, a.itemprice, b.imagename, b.status 
FROM table1 a 
LEFT OUTER JOIN table2 AS b ON a.cid = b.cid 
GROUP BY a.cid, a.itemdesc, a.itemprice;