从相关表中选择最大值

时间:2012-07-12 16:30:10

标签: mysql sql

在我的应用程序中,我想选择table1中的所有数据和相关table2的最大id。问题是,如果table2中有实体,SQL工作正常。但如果不是,那么restulset就会填充NULL:

SELECT table1.*, CONCAT(table1.number, '-', table1.item_id) AS IdNumber, MAX(table2.id) AS Table2Id
  FROM table1
  LEFT JOIN table2 ON (table1.ID = table2.EQUIP_ITEM_ID)
WHERE table1.GROUP_ID > 0
  AND table2.IN_PROGRESS = 1
ORDER BY table1.ID ASC
LIMIT 15 

我需要更改什么才能检索到正确的结果集?

3 个答案:

答案 0 :(得分:1)

问题在于第二个WHERE条件table2.IN_PROGRESS = 1

如果您仍希望显示table1数据,请将SQL修改为

(table2.IN_PROGRESS = 1 OR table2.IN_PROGRESS IS NULL)

如果您想将0显示为值,请将MAX(table2.id)更改为COALESCE(MAX(table2.id),0)

答案 1 :(得分:1)

试试这个::

SELECT table1.*, CONCAT(table1.number, '-', table1.item_id) AS IdNumber, MAX(IFNULL(table2.id),0) AS Table2Id
  FROM table1
  LEFT JOIN table2 ON (table1.ID = table2.EQUIP_ITEM_ID)
WHERE table1.GROUP_ID > 0
  AND table2.IN_PROGRESS = 1
ORDER BY table1.ID ASC
LIMIT 15

答案 2 :(得分:1)

SELECT table1。*,CONCAT(table1.number,' - ',table1.item_id)AS IdNumber,MAX(table2.id)AS Table2Id

FROM table1

LEFT JOIN table2 ON(table1.ID = table2.EQUIP_ITEM_ID)

WHERE table1.GROUP_ID> 0

AND table2.IN_PROGRESS = 1

AND IS NOT NULL(table2.IN_PROGRESS)

ORDER BY table1.ID ASC

LIMIT 15

一定没问题;)