1

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

但我只希望查询只返回表 1 中每条记录的第一行

谢谢

4

4 回答 4

2

我同意 John Woo 上面的回答。您需要某种子查询来实际检索表 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)
于 2012-11-07T08:19:25.573 回答
1

您需要创建一个额外的子查询,imagename每个 cid. 尝试这个,

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
于 2012-11-07T07:42:43.100 回答
0
Select 
    distinct a.cid,a.itemdesc,b.imagename,a.itemprice,b.status
from table1 a,
table2 b
where a.cid=b.cid
于 2012-11-07T07:43:10.427 回答
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;
于 2012-11-07T08:45:30.833 回答