如何为每个唯一值和特定条件选择具有最小日期的第一行

时间:2015-12-14 01:12:08

标签: mysql

我有下表

表1

------------------------------------------
| animal_id | animal_name | animal_type |
------------------------------------------
|     1     | kay         | cat         |
|     2     | sandy       | dog         |
------------------------------------------

表2

--------------------------------------------------------------------------
| vaccine_id | animal_id  | vaccine_name | vaccine_status | vaccine_date |
--------------------------------------------------------------------------
| 1          | 1          | rabies       | done           | 2015-09-09   |
| 2          | 1          | chlamydiasis | undone         | 2015-09-15   |
| 3          | 1          | parasite     | undone         | 2015-10-20   |
| 4          | 2          | parasytosis  | undone         | 2015-11-10   |
| 5          | 2          | rabies       | undone         | 2015-11-05   |

预期结果:

    --------------------------------------------------------------------------------------------------------------
    | animal_id  | animal_name | animal_type | vacccine_id  | vaccine_name | vaccine_status  |  vaccine_date  |
    --------------------------------------------------------------------------------------------------------------
    | 1          | kay         | cat         | 2            | chlamydiasis | undone          | 2015-09-15     | 
    | 2          | sandy       | dog         | 5            | rabies       | undone          | 2015-11-05     |

结果将显示两个表之间每个唯一值的第一行,其中包含最新的vaccine_date以及撤消vaccine_status的条件。我顺便使用SQL

1 个答案:

答案 0 :(得分:0)

对于复杂查询,您经常需要使用PHP之类的操作来处理数据。例如,对您提供的数据使用2个查询:

<?php
    $link=mysqli_connect("host","user","password","database");
    // Start with the list of animals
    $sql = "SELECT * FROM animals";
    $res = $link->query($sql);
    for($i=0; $i<mysqli_num_rows($res); ++$i){
        $row1 = mysqli_fetch_assoc($res);
        $animal_id = $row1['animal_id'];
        $sql = "SELECT * FROM vaccines WHERE animal_id = $animal_id AND vaccine_status = 'undone' ORDER BY vaccine_date ASC LIMIT 1";
        $res2 = $link->query($sql);
        $row2 = mysqli_fetch_assoc($res2);
        $arr[$animal_id] = array();
        array_push($arr[$animal_id], $row1['animal_name'], $row1['animal_type'], $row2['vaccine_id'], $row2['vaccine_name'], $row2['vaccine_status'], $row2['vaccine_date']);
    }

    echo "RESULT:";
    echo "<table border=1><tr><th>animal_id</th><th>animal_name</th><th>animal_type</th><th>vaccine_id</th><th>vaccine_name</th><th>vaccine_status</th><th>vaccine_date</th></tr>";
    foreach($arr as $key => $val){
        echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
    }
?>

...产生以下输出:

output from code