Mysql 根据计划从中获取数据

Mysql 根据计划从中获取数据,mysql,Mysql,嗨,我有下表- 我想通过location_id根据计划从该表中获取活动_id,如果根据当前计划找不到活动_id,则我需要默认活动_id(默认值>0)。我需要你们的帮助。如果你建议我优化桌子,我会改变我的桌子 对不起,我的英语很差。它没有经过测试。我想这对你完全有帮助 select * from ( select *,count(*) as cnt,1 as ord from table1 t inner join schedule

嗨,我有下表-

我想通过location_id根据计划从该表中获取活动_id,如果根据当前计划找不到活动_id,则我需要默认活动_id(默认值>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
DB:

x、 php


“基于计划”-意思是?你能提供正确的信息吗?我是指当前数据时间,请重新查看我的表格我添加了更多数据请建议我的任何最简单的解决方案意味着你想要基于当前日期和时间的活动id?我不知道你的表格名称。那么我只简单地说是表1
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)
<?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, )