如何按列分组两行

时间:2016-03-11 12:36:07

标签: mysql

我有两个表数据和位置 表数据保存位置,ID,名称... 表位置保持位置和ID ...

table location
id    location
1     offshore
2     onsite

id   location    name
1      offshore   A
2      offshore   B
3      offshore   C

如何获得输出

id location Name
1    offshore   A
1    onsite     Null

2 个答案:

答案 0 :(得分:0)

data上的左连接data表格可以获取所有位置,无论select l.id, l.location, min(d.name) as name from location l left join data d on l.location=d.location group by l.id, l.location 表中是否匹配,按位置ID和位置分组,我认为您想获得第1个name(min()):

select d.id, l.location, d2.name
from location l
join data d
left join data d2 on l.location=d2.location
where d.id=1

或者,如果您想获得数据项,如果它有离岸和在岸记录:

<?php


// Indicate the location of your images 
$root = '';
// use if specifying path from root
$path = 'images/';

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            // Checks for file formats
            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

function getRandomFromArray($ar) {
    mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
    $num = array_rand($ar);
    return $ar[$num];
}


// Collects list of images from directory 
$imgList = getImagesFromDir($root . $path);

$img = getRandomFromArray($imgList);
?> 

答案 1 :(得分:-1)

select * from data d left join location l on l.location=d.location group by location