简体   繁体   中英

Get column value with same row id

I got this MYSQL table:

+---------------+   
|ID|OID|   mpn  |
+--+---+--------+  
|1 | 1 |  12345 |
|2 | 1 |  54321 |
|3 | 2 |  78912 |
|4 | 2 |  12431 |
|5 | 2 |  78787 |
|6 | 3 |  14565 |
.................

Now I want to set the values [mpn] for each [OID] in an array.
Something like this:

$oid1 = array([mpn1], [mpn2])
$oid2 = array([mpn1], [mpn2], [mpn3])...... 

Or just manage to output the [mpn] referring to [OID] . So, I want to get every MPN referring to OID=1 , for example. So, how do I select those values out of the table?

Here used COALESCE() and GROUP_CONCAT Functions.

The GROUP_CONCAT function concatenates strings from a group into one string with various options.

The COALESCE function evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

select t.OID,COALESCE( GROUP_CONCAT( t.mpn) , '' ) as mpn
from tableName t 
group by t.OID

If mpn have any null value then you can fill up this null value with any String or null. That u want to do.

I think you want group_concat() :

select oid, group_concat(mpn) as mpns
from t
group by oid;

This creates the list of mon as a comma-delimited list which you can parse in php.

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