在第一个表上加入两个带条件的表

时间:2014-04-09 08:53:37

标签: mysql prepared-statement

我想将这两个组合成一个SELECT语句:

SELECT * 
FROM activegroupmodel 
WHERE groupID = ? 
ORDER BY groupModelID DESC 
LIMIT 1

SELECT * 
FROM model 
WHERE modelID = ?

正如您从第一个组中看到的那样,ID不是pk,我想要该表中的最新模型。 我试过这个,但显然没有用:

SELECT * 
FROM activegroupmodel as a 
WHERE a.groupID = ? 
ORDER BY a.groupModelID DESC 
LIMIT 1 
INNER JOIN model as m ON a.modelID = m.modelID

我已经通过JOIN阅读了一堆问题,但没有一个问题符合我的问题。 谁知道我怎么解决这个问题? 最好的问候约翰

4 个答案:

答案 0 :(得分:1)

将你的JOIN放在WHERE条件之前,如下所示:

SELECT * 
FROM activegroupmodel as a
INNER JOIN model as m ON a.modelID = m.modelID
WHERE a.groupID = ? 
ORDER BY a.groupModelID DESC 
LIMIT 1 

答案 1 :(得分:0)

SELECT * 
FROM activegroupmodel as a 
INNER JOIN model as m ON a.modelID = m.modelID
WHERE a.groupID = ? 
ORDER BY a.groupModelID DESC 
LIMIT 1 

答案 2 :(得分:0)

正确的连接语句应为

SELECT * 
FROM activegroupmodel as a 
INNER JOIN model as m ON a.modelID = m.modelID
WHERE a.groupID = ? 
ORDER BY a.groupModelID DESC 
LIMIT 1 

答案 3 :(得分:0)

试试这个

SELECT * 
FROM activegroupmodel as a 
INNER JOIN model as m ON a.modelID = m.modelID
WHERE a.groupID = ? 
ORDER BY a.groupModelID DESC 
LIMIT 1