1

在我的应用程序中,我想从 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 

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

4

3 回答 3

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)

于 2012-07-12T16:35:43.707 回答
1

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

从表 1

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

WHERE table1.GROUP_ID > 0

AND table2.IN_PROGRESS = 1

AND 不为 NULL (table2.IN_PROGRESS)

ORDER BY table1.ID ASC

限制 15

应该没问题;)

于 2012-07-12T16:51:08.147 回答
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
于 2012-07-12T16:38:58.593 回答