简体   繁体   中英

SQL: can I JOIN 2 tables according the first table “array” value?

Im trying to find a better way to return 2 tables at once.

My first table is:

[ID]       [area]
  1        13,12,15
  6        18,17,13

and the second table is:

 [areaname]    [singlearea]
 textOf12     12
 textOf18     18
 textOf15     15

Now, I need to return for each [ID] hits area names, for example:

For the ID: 1, I need the following array: (textOf12,textOf15)

and for the ID 6 I need: (textOf18) only.

This is what i have for now (I don't think its a nice code):

$getall = "SELECT * FROM table1";
$resultfull = mysql_query($getall);
while ($res = mysql_fetch_assoc($resultfull))
{
$uarray = array();
$sqlarea = explode(",", $res['area']);

foreach($sqlarea as $userarea)
        {
        $areaarray = runquery("SELECT areaname From table2 WHERE singlearea = '".$userarea."'");
        $value = mysql_fetch_object($areaarray);
        array_push($uarray,$value->areaname);
        }
var_dump($uarray);

any suggestions?

Thank you very much!

Comma separated ID list and ID value pretty good matching using like :

select t1.id, t2.areaname
  from table1 t1, table2 t2
  where concat(',', t1.area, ',') like concat('%,', t2.singlearea, ',%')

However It's recommended to use additional link table!

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