MYSQL Left join A.table and b.table while retaining a.table id

怎甘沉沦 提交于 2019-12-25 08:13:48

问题


MYSQL Left join A.table and b.table while retaining a.table id when there is no b.table match.

SELECT * FROM sales_customer a LEFT JOIN sales_contact b
ON a.customer_id = b.customer_id
ORDER BY CASE WHEN company_name = '' THEN lname ELSE company_name END ASC

Gets me this:

Array (
  [0] => 54
  [customer_id] => 
)

When there is no b.table match.

I need this:

Array (
  [0] => 54
  [customer_id] => 29 
)

Any suggestions?

The solution below worked. Thanks for your help.

SELECT *, COALESCE(a.customer_id, 0) AS customer_id FROM sales_customer a LEFT OUTER JOIN sales_contact b ON a.customer_id = b.customer_id ORDER BY CASE WHEN company_name = '' THEN lname ELSE company_name END ASC


回答1:


Use it like this:

SELECT 
    *,
    COALESCE(b.customer_id, 0) AS customer_id
FROM sales_customer a 
LEFT JOIN sales_contact b ON a.customer_id = b.customer_id
ORDER BY 
    CASE WHEN company_name = '' THEN lname ELSE company_name END ASC



回答2:


Try using COALESCE(). It will return the first non-NULL value.




回答3:


Instead of writing SELECT * ("select all fields"), you should specify the fields you actually want: SELECT 54 AS `0`, a.customer_id, ... FROM .... That's better practice in general, not just for this.

If you really want to write SELECT * to select all fields, you can still add additional fields to the end, which in PHP will overwrite earlier like-named fields: SELECT *, a.customer_id FROM ....



来源:https://stackoverflow.com/questions/9568530/mysql-left-join-a-table-and-b-table-while-retaining-a-table-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!