获取同一行的多个值

时间:2015-10-19 16:48:46

标签: php mysql

我的表A包含

id | data
1     10
2     20

和表B包含

id | a_id | value
1     1       abc
2     1       def
3     2       ghi

表B的列a_id引用表A的列id。我必须从表A中检索最后4行数据及其对应的表B.当我尝试使用此查询检索它时

SELECT * FROM tableA INNER JOIN tableB ON tableA.id = tableB.id ORDER BY tableA.id DESC LIMIT 4

我从表A中获得了重复的第1行

id | data | value
1     10     abc
1     10     def
2     20     ghi 

有没有什么方法可以减少这些重复数据所以我可以获得id 1的单行及其两个值?

3 个答案:

答案 0 :(得分:0)

您可以使用app.controller("myController", ['$scope', function ($scope) { // object must be empty initialize,so it can be appended $scope.injectedObject = {}; // now i can directly calling invoke function from here $scope.injectedObject.invoke(); }]; 执行此操作,请参阅此处的文档https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

GROUP_CONCAT

答案 1 :(得分:0)

请使用此查询:

app.get('/export/siteoccupancy', function(req,res){      

    if(_.isEmpty(req.query)){
         res.status(404).send('requires a start and end date');
    }else{
        //getting paramas
        var sDate = req.query.startDate;
        var eDate = req.query.endDate;

    }

    var fs = require('fs');
    var archiver = require('archiver');

    var archive = archiver('zip');

    archive.on('err',function(err){
        res.status(500).send({error : err.message});
    });

    res.on('close',function(){
        console.log('Archive size : %d b',archive.pointer());
        return res.status(200).send('OK').end();
    });

    res.attachment('data-export.zip');

    archive.pipe(res);

    var stream = fs.createWriteStream("data-report.txt')");
    stream.once('open',function(fd) {
        stream.write('test1');
        stream.write('\n test2');
        stream.write('\n test3');
        stream.end();
    });

    archive.append(stream);

    archive.finalize();

});

答案 2 :(得分:0)

只需在PHP中进行后处理,例如:

$data = [];
while ($row = $result->fetchAssoc()) {  // or whatever you do to fetch your data
    if (!isset($data[$row['id']])) {
        $row['value'] = [$row['value']];
        $data[$row['id']] = $row;
    } else {
        $data[$row['id']]['value'][] = $row['value']
    }
}

给你一个很好的结果,如:

[
    1 => [
        id => 1,
        data => 10,
        value => ['abc', 'def']
    ]
    ..
]