如何使用nl2br从另一个表中使用连接名称回显结果

时间:2017-12-07 19:08:13

标签: php mysql inner-join

我知道如何使用以下

回显数组中的结果
nl2br(str_replace(',', "\n", $row['column-name']))

我现在有一个列,其中列出的项目(以逗号分隔)是与另一个表对应的id号。

如何回显这些结果并将与该项关联的名称应用于其ID?

我尝试过INNER JOIN,但我似乎错过了如何正确执行此操作。

'SELECT * FROM Table1 
 INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnID
 INNER JOIN Table3 ON Table1.ColumnID2 = Table3.ColumnID2 <-- This needs to apply names to the number-ids split by the nl2br
 ORDER BY OrderColumn'

<span>'.nl2br(str_replace(',', "\n", $row['table3-column-name-to-replace-table1-columnID2'])).'</span>

感谢您的帮助。

这是预期的结果。 https://drive.google.com/file/d/1ChGv9qHeJPgtwVcxbqj8ey-1RjVTah28/view?usp=sharing

1 个答案:

答案 0 :(得分:0)

要获取Table3列表中显示的所有Table1行,您需要相应地更改您的JOIN:

SELECT 
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM 
    Table1 
    INNER JOIN Table2 
        ON Table1.State = Table2.ID
    INNER JOIN Table3 
        ON Table1.Counties LIKE Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID
        OR Table1.Counties = Table3.ID
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;

结果将是:

[
    ['John Doe', 'Missouri', 'Apple County
                              Orange County
                              Grape County
                              Banana County']
]

缺点是,DB需要在每一行上执行多次文本比较,这意味着执行JOIN的速度非常慢。

更好的解决方案是编辑Table3,不仅要保留自己的ID,还要保存Table1的ID,作为外键/父参考。

START TRANSACTION;
ALTER TABLE Table3 ADD coverageAreaID INT NOT NULL;
ALTER TABLE Table3 ADD CONSTRAINT fk_covarea_state FOREIGN KEY (coverageAreaID) REFERENCES Table1(ID);
UPDATE Table3 SET coverageAreaID = (
    SELECT 
        Table1.ID 
    FROM 
        Table1
    WHERE
        Table1.Counties LIKE Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID 
        OR Table1.Counties = Table3.ID 
    LIMIT 1;
);
COMMIT;

像这样,您可以使用以下SQL查询:

SELECT 
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM 
    Table1 
    INNER JOIN Table2 
        ON Table1.State = Table2.ID
    INNER JOIN Table3 
        ON Table1.ID = Table3.coverageAreaID 
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;

此查询现在将导出与上面相同的结果,但速度会快得多,因为它可以通过简单的数字比较来连接表。

现在使用您的代码应该没有问题:

  

nl2br($行[ '县'])