从sql中搜索多个关键字

时间:2011-02-09 19:03:21

标签: php sql

所以我从sql获取数据:

$date = 1-02-2011
$sql = "SELECT * FROM abc  WHERE date='$date'"

现在我想从多个日期获取数据以创建图表

$date1 = 1-02-2011
$date2 = 2-02-2011
$date3 = 3-02-2011
$date4 = 4-02-2011
$date5 = 5-02-2011
$date6 = 6-02-2011

依旧......

有什么快捷方式吗?或者必须为每个日期创建不同的查询?

1 个答案:

答案 0 :(得分:2)

您可以使用IN:

SELECT * FROM abc WHERE date IN ('2011-02-01', '2011-02-03', '2011-02-05')

或者如果你的日期总是像你的例子一样连续,那么你可以使用BETWEEN:

SELECT * FROM abc WHERE date BETWEEN '2011-02-01' AND '2011-02-06'

然后阅读结果:

$result = mysql_query($query) or trigger_error(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
    $date =  $row['date'];
    $col1 = $row['col1'];
    // Do something with the results.
}

编辑:要显示缺失值的NULL,可以使用LEFT JOIN:

SELECT T1.date, T2.*
FROM (
    SELECT '2011-02-01' AS date
    UNION ALL
    SELECT '2011-02-02'
    UNION ALL
    ...
    UNION ALL
    SELECT '2011-02-06'
) AS T1
LEFT JOIN T2
ON T1.date = T2.date