MySQL:当一个表上存在多个连接时,计算NULL或0值

时间:2017-08-25 16:57:02

标签: php mysql sql

我有一个查询,根据他们在名为users的表中的记录ID查找人的全名。全名与另一个表(table1)中的角色相关联。这需要多个连接到users表:

SELECT table1.id, users.full_name AS "Requester", 
users.full_name AS "Approver," 
users.full_name AS "Ordered By", 
users.full_name AS "Received By" 
FROM table1
JOIN users AS users
ON table1.requester_id = users.id
JOIN users AS users2
ON table1.approver_id = users2.id
JOIN users AS users3 
ON table1.ordered_by = users3.id
JOIN users AS users4
ON table1.received_by = users4.id
WHERE table1.deleted_record !=1;

我遇到的问题是ordered_byreceived_by。通常,它们还不存在,因为订单既没有被订购也没有收到,因此每个订单的ID可以是0,这在users表中没有相应的值。当我运行这个查询时,我应该找回所有存在的475条记录,但由于这些0值,我只能返回365条。如何修改此查询以确保返回所有行,即使ordered_by和/或received_by = 0?

2 个答案:

答案 0 :(得分:2)

首先,驱动查询的主表应为table1。然后,您使用JOIN代替LEFT JOIN。如果没有链接,LEFT JOIN会给你一个空结果,但不会失败。在这种情况下,您可能必须使用IF作为字段值

SELECT table1.id, req.full_name AS "Requester", 
   app.full_name AS "Approver", 
   ordr.full_name AS "Ordered By", 
   rec.full_name AS "Received By" 
FROM table1
LEFT JOIN users AS req
   ON table1.requester_id = req.id
LEFT JOIN users AS app
   ON table1.approver_id = app.id
LEFT JOIN users AS ordr
   ON table1.ordered_by = ordr.id
LEFT JOIN users AS rec
   ON table1.received_by = rec.id
WHERE table1.deleted_record !=1;

这应该这样做

答案 1 :(得分:1)

您正在寻找left join

SELECT t1.id, ur.full_name AS "Requester", 
       ua.full_name AS "Approver," 
       uo.full_name AS "Ordered By", 
       urv.uo AS "Received By" 
FROM table1 t1 LEFT JOIN
     users ur
     ON t1.requester_id = ur.id LEFT JOIN
     users ua
     ON t1.approver_id = ua.id LEFT JOIN
     users uo 
     ON t1.ordered_by = uo.id LEFT JOIN
     users urv
     ON t1.received_by = urv.id
WHERE t1.deleted_record <> 1;

请注意,我将users引用上的别名从无意义的u1u2等更改为uauo,依此类推。此外,需要在SELECT中使用这些来获取正确的全名。