我有一个像这样的查询
Select * from tableA A
LEFT JOIN
mydb.tableB B
ON A.pk = B.tableA_pk
LEFT JOIN
mydb.tableC C
ON B.tableC_pk = C.pk
WHERE C.PK IN ('325','305', '322')
ORDER BY A.pk desc;
这将返回一个类似的结果,可能有多行用于适用的条目
4, xxx, yyy, 325, 325, zzz <<<< most recent for this entry ( 'unique' key is tableC.pk, 325)
3, aaa, bbb, 325, 325, eee <<<< next most recent
3, ccc, ddd, 322, 322, fff
2, eee, fff, 305, 305, rrr
2, ggg, hhhh,322, 322, ttt
1, iii, jjj, 325, 325, uuu <<< oldest
理想情况下,我希望结果如下所示,即LIST ..IN中的每个匹配条目(&#39; 325&#39;,&#39; 322&#39;)它应该只返回最多最近的条目如下
4, xxx, yyy, 325, 325, zzz <<<< most recent
3, ccc, ddd, 322, 322, fff
2, eee, fff, 305, 305, rrr
进一步解释..
Select * from tableA A
LEFT JOIN
mydb.tableB B
ON A.pk = B.tableA_pk
LEFT JOIN
mydb.tableC C
ON B.tableC_pk = C.pk
WHERE C.PK IN ('325')
ORDER BY A.pk desc;
我会得到这个
4, xxx, yyy, 325, 325, zzz <<<< most recent for this entry
3, aaa, bbb, 325, 325, eee <<<< next most recent
1, iii, jjj, 325, 325, uuu <<< oldest
但我需要这个:
4, xxx, yyy, 325, 325, zzz <<<< most recent for this entry ( 'unique' key is tableC.pk)
我已经尝试了LIMIT 1(我使用MySQL),如下所示,但在我的查询列表中,每个搜索条目的总请求数限制为1,而不是1。
Select * from tableA A
LEFT JOIN
mydb.tableB B
ON A.pk = B.tableA_pk
LEFT JOIN
mydb.tableC C
ON B.tableC_pk = C.pk
WHERE C.pk IN ('325','305', '322')
ORDER BY A.pk desc
LIMIT 1;
答案 0 :(得分:0)
你可以使用1来迭代它来使用变量。
Select A.*, @i:=@i+1 AS rownum
from tableA A
LEFT JOIN
mydb.tableB B
ON A.pk = B.tableA_pk
LEFT JOIN
mydb.tableC C
ON B.tableC_pk = C.pk
WHERE C.PK IN ('325') and (SELECT @i:= 0) r
ORDER BY A.pk desc;
注意:我还没有测试过上面的查询。
答案 1 :(得分:0)
在阅读建议和其他答案之后,我就这样实现了......非常感谢所有的帮助......
SELECT
DISTINCT C.PK
,B.PK
,B.tableC_pk
,B.tableA_pk
,A.pk
FROM
tableC C
INNER JOIN
tableB B
ON C.PK = B.tableC_pk
INNER JOIN
tableA A
ON A.PK = B.tableA_pk
INNER JOIN ( SELECT tableC_pk,MAX(PK) AS PK FROM tableB
WHERE tableC_pk IN ('325','322','111')
GROUP BY 1) D
ON C.PK = B.tableC_pk
AND B.PK = D.PK
答案 2 :(得分:-1)
这个问题每天都要问几次。在这里你会找到答案: