嗨,我有以下表格 - Location Schedule
我希望通过location_id根据时间表从此表中获取campaign_id,如果根据当前时间表找不到campaign_id,则我需要默认的campaign_id(默认值> 0)。我需要你的帮助。如果你给我建议任何优化表,我会改变我的表。
抱歉我的英语不好。
答案 0 :(得分:0)
未经测试。我认为它的帮助完全适合你
select * from (
select *,count(*) as cnt,1 as ord from table1 t
inner join schedule s on s.location_id=t.location_id
and now() between start_date and end_date
union all
select *,count(*) as cnt,1 as ord from table1 t
inner join schedule s on s.location_id=t.location_id
and default_id > 0
) as tt where ord= case when (ord=1 and cnt > 0) then 1 else 2 end
答案 1 :(得分:0)
DB:
mysql> select * from schedule_table;
+----+-------------+-------------+
| id | campaign_id | location_id |
+----+-------------+-------------+
| 1 | 5 | 10 |
| 2 | 10 | 5 |
| 3 | 7 | 11 |
| 4 | 6 | 12 |
| 5 | 8 | 13 |
+----+-------------+-------------+
5 rows in set (0.00 sec)
x.php
<?php
$id = $argv[1];
$dbh = new PDO('mysql:dbname=test;host=127.0.0.1', 'root');
$sth = $dbh->prepare(
'
SELECT
d.campaign_id AS default_id,
a.campaign_id AS actual_id
FROM schedule_table AS d
LEFT JOIN schedule_table As a ON a.location_id = :id
WHERE
d.campaign_id > 0
ORDER BY d.campaign_id
LIMIT 1
'
);
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
var_export($result);
结果:
php x.php 12 array ( 'default_id' => '5', 'actual_id' => '6', ) php x.php 125 array ( 'default_id' => '5', 'actual_id' => NULL, )