gpt4 book ai didi

php - 当连接的表有多个匹配项并且 GROUP BY 省略需要的行时,如何从 LEFT JOINs 制作一个数组

转载 作者:行者123 更新时间:2023-11-29 00:11:18 25 4
gpt4 key购买 nike

今天我遇到了一些与 PHP/MYSQL 相关的问题,但我不确定如何处理。

我正在针对更改后的 vbulletin 数据库运行此查询:

SELECT
p.postid,
p.threadid,
p.parentid,
p.username,
p.title,
p.dateline,
p.pagetext,
p.allowsmilie,
p.visible,

pe.post_type,
pe.element_type,
pe.element,

pr.region_id,

th.threadid,
th.title,
th.forumid,
th.lastpost,
th.lastposter,
th.lastpostid,
th.similar,

at.contentid,
at.attachmentid,

p.attach


FROM thread AS th

JOIN post as p ON p.threadid = th.threadid
LEFT JOIN post_element AS pe ON pe.post_id = p.postid
LEFT JOIN post_region AS pr ON pr.post_id = p.postid
LEFT JOIN attachment AS at ON at.contentid = p.postid

GROUP BY p.postid;

上面的问题是,有时 post_element 中有 2、3 或 4 行具有相同的 post_id == p.postid。在那种情况下,GROUP BY 返回第一个匹配项并忽略第二个第三个....等....

我真正想要的是创建一个类似于这样的数组:

while ($row = mysql_fetch_assoc($result)) {

}

当 post_id 有多个匹配项时,为 pe.element、pe.post_type、pe.element_type 字段构建嵌套数组。

我能够通过使用这个来破解它:

SELECT
p.postid,
p.threadid,
p.parentid,
p.username,
p.title,
p.dateline,
p.pagetext,
p.allowsmilie,
p.visible,

group_concat(pe.post_type) as post_type,
group_concat(pe.element_type) as element_type,
group_concat(pe.element) as element,

group_concat(pr.region_id) as region_id,

th.threadid,
th.title,
th.forumid,
th.lastpost,
th.lastposter,
th.lastpostid,
th.similar,

at.contentid,
at.attachmentid,

p.attach


FROM thread AS th

JOIN post as p ON p.threadid = th.threadid
LEFT JOIN post_element AS pe ON pe.post_id = p.postid
LEFT JOIN post_region AS pr ON pr.post_id = p.postid
LEFT JOIN attachment AS at ON at.contentid = p.postid

GROUP BY p.postid'

然后 $row['element'] = explode(",", $row['element']);

在前面提到的 mysql_fetch_assoc while 循环中...

但是您如何使用 PHP 制作一个数组,每个 post_id == postid 只有一个 $row,并为从 $result 中有多个匹配项的字段嵌套数组?

非常非常感谢您的脑力!

最佳答案

我会像你目前一样选择第一个,向查询添加一个 count(pe.post_id) 如果该数字大于 1,则直接查询该表

如果 > 50% 的人有超过 1 个,那么总是使用第二个查询,从不检查它。

所以

//do main query
foreach($post as &$p) {
$elements = array();
$p['elements'] = getElements($p['postid'])
}

关于php - 当连接的表有多个匹配项并且 GROUP BY 省略需要的行时,如何从 LEFT JOINs 制作一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com