简体   繁体   中英

How to merge two table rows column having same field based on null and not null and result into a single row?

I am working on Web based Application using PHP & MySQL for few few years. I am having problem with my query for some days. Please help if possible...

My Scenario

I have two table like following:

TABLE1

| m_id | COL1 | COL2 | COL3 | COL4 |
|  1   |   1  |   0  |  0   |   1  |
|  2   |   0  |   1  |  0   |   0  |

TABLE2

| m_id | COL1 | COL2 | COL3 | COL4 |
|  2   |   1  |   0  |  0   |   0  |

According to my project scenario i have to put two table same column. m_id 2 is reference in table 2 from table1. I need to query these tables that result with the following row:

Query Result

| m_id | COL1 | COL2 | COL3 | COL4 |
|  2   |   1  |   1  |  0   |   0  |

I need result comparing two rows according to null and not null values. I hope i may make it understandable for you! I tied this for some days. I got some hints of using coalesce() function. But could not reach the desired outcome!!!

You could do something like this:

SELECT 
  COALESCE (a.col1, b.`col1`) AS col1,
  COALESCE (a.col2, b.`col2`) AS col2,
  COALESCE (a.col3, b.`col3`) AS col3,
  COALESCE (a.col4, b.`col4`) AS col4 
FROM
  a 
INNER JOIN b 
ON (a.id = b.id) ;

It looks like you need the operation "AND" for the values in the columns. If so:

SELECT Table1.m_id, (Table1.COL1 AND Table1.COL2) AS COL1 /* ,same for the rest of the columns */ FROM Table1 LEFT JOIN  Table2 ON Table1.m_id=Table2.m_id 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM