其实我有以下代码:
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
我试着解释一下我想做什么:
检查列all
中是否有包含city
的行。
如果是,请检查date_created
中此行的日期是否比上述查询的最新条目中的日期更新。如果是,请选择此行,否则请选择下面查询的最新条目。
我希望你明白我想做什么。不幸的是,我不熟悉SQL中的if / else语句。
有人能帮助我吗?
答案 0 :(得分:1)
我认为这可以简化。
看起来您应该只能选择城市是您的参数或“全部”的行,按照date_created
的顺序排序,然后选择第一行。
$sql = "SELECT id, city FROM news
WHERE city IN(:city, 'all')
ORDER BY date_created DESC LIMIT 1";
由于您知道您的查询只会返回一行,因此您只需使用fetch
代替fetchAll
来消除不必要的外部数组。
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':city' => $city));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
答案 1 :(得分:0)
因为我不熟悉SQL中的if / else语句,但在PHP中我做了以下工作:
<?php
$stmt = $pdo->prepare('SELECT id, city, date_created FROM news WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
$results = $stmt->fetchAll();
foreach( $results as $row ) {
$date_city = $row['date_created'];
}
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = "all" ORDER BY date_created DESC LIMIT 1');
$stmt->execute();
$results = $stmt->fetchAll();
foreach( $results as $row ) {
$date_all = $row['date_created'];
}
if ($date_all > $date_city) {
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = "all" ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
} else {
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
}
?>