我正在尝试找到一种更好的方法来一次返回 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/