php - SQL : can I JOIN 2 tables according the first table "array" value?

标签 php mysql arrays join

我正在尝试找到一种更好的方法来一次返回 2 个表。

我的第一个表是:

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

第二个表是:

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

现在,我需要返回每个 [ID] 命中的区域名称,例如:

对于 ID: 1,我需要以下数组:(textOf12,textOf15)

对于 ID 6,我只需要:(textOf18)

这就是我现在所拥有的(我认为它不是一个好的代码):

$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);

有什么建议吗?

非常感谢!

最佳答案

逗号分隔的 ID 列表和 ID 值使用 like 可以很好地匹配:

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

但是建议使用额外的链接表!

关于php - SQL : can I JOIN 2 tables according the first table "array" value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972136/

相关文章:

mysql - 获取 MySQL 数据库中所有表的记录数

PHP Implode 无法与 mysql_query 一起使用

c - C 有没有办法从函数返回整个数组?

c - 如何将指向数组的指针传递给函数?

php - CakePHP 获取 IP 地址

php - 如何在 PHP 中显示 MySQL 查询的执行时间?

php 和 sql 'INSERT INTO' 未填充 sql 数据库

javascript - Laravel 分页表 - 对一列进行排序

mysql - 左连接返回重复值

PHP - 只接受特定类的数组