我在 StackOverflow 上看到了以下问题, Intelligent MySQL GROUP BY for Activity Streams 由 Christian Owens 12/12/12 发布。
所以我决定尝试相同的方法,制作两个与他的相似的表格。然后我几乎复制了我理解的他的查询。 这是我从沙箱中得到的:
Array
(
[0] => Array
(
[id] => 0
[user_id] => 1
[action] => published_post
[object_id] => 776286559146635
[object_type] => post
[stream_date] => 2015-11-24 12:28:09
[rows_in_group] => 1
[in_collection] => 0
)
)
我很好奇,自从查看Owens 问题的结果后,我无法完全得到一些东西,他是否执行额外的查询来获取实际的元数据?如果是,这是否意味着可以从单个查询执行此操作,或者是否需要运行不同的优化子查询然后循环遍历数据数组以呈现流本身。
非常感谢。
Array
(
[0] => Array
(
[id] => 0
[user_id] => 1
[fullname] => David Anderson
[action] => hearted
[object_id] => array (
[id] => 3438983
[title] => Grand Theft Auto
[Category] => Games
)
[object_type] => product
[stream_date] => 2015-11-24 12:28:09
[rows_in_group] => 1
[in_collection] => 1
)
)
最佳答案
在“伪”代码中你需要这样的东西
$result = $pdo->query('
SELECT stream.*,
object.*,
COUNT(stream.id) AS rows_in_group,
GROUP_CONCAT(stream.id) AS in_collection
FROM stream
INNER JOIN follows ON stream.user_id = follows.following_user
LEFT JOIN object ON stream.object_id = object.id
WHERE follows.user_id = '0'
GROUP BY stream.user_id,
stream.verb,
stream.object_id,
stream.type,
date(stream.stream_date)
ORDER BY stream.stream_date DESC
');
然后解析结果并在php中转换
$data = array(); // this will store the end result
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
// here for each row you get the keys and put it in a sub-array
// first copy the selected `object` data into a sub array
$row['object_data']['id'] = $row['object.id'];
$row['object_data']['title'] = $row['object.title'];
// remove the flat selected keys
unset($row['object.id']);
unset($row['object.title']);
...
$data[] = $row; // move to the desired array
}
你应该得到
Array
(
[0] => Array
(
[id] => 0
[user_id] => 1
[fullname] => David Anderson
[verb] => hearted
[object_data] => array (
[id] => 3438983
[title] => Grand Theft Auto
[Category] => Games
)
[type] => product
[stream_date] => 2015-11-24 12:28:09
[rows_in_group] => 1
[in_collection] => 1
)
)
关于php - 使用元数据推送指向关注者的指针(MySQL 查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895563/