如何根据第一个查询结果执行第二个查询

时间:2017-07-07 16:35:58

标签: mysql sql database

根据第一个execute结果,我需要query query

这是我的第一个查询结果:

id  current_date    starts_on   ends_on Product_id  days_remaining
1   2017-06-21T12:00:00 2017-06-20T12:00:00Z    2017-06-23T12:00:00Z    3   2
2   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    4   0
3   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    7   0
4   2017-06-21T12:00:00 2017-07-01T12:00:00Z    2017-07-03T12:00:00Z    5   12

在这里,您可以看到remaining_days有两个零(0)作为结果,我想从product_name表product >

  

My Both the Tables和Query for Above结果已实现,但是   获取product_name未实现。请帮帮我

这是我的sqlfiddle: http://sqlfiddle.com/#!9/5bf34/1

我的问题:如果product_name(见上面的结果)为0,我希望得到所有days_remaining

  

简而言之,如果days_remaining为0,则获取所有product_name

3 个答案:

答案 0 :(得分:0)

您可以使用以下解决方案:

SET @mycurrentDate = '2017-06-21T12:00:00';
SELECT p.product_name, tn.* FROM (
    SELECT 
        id, 
        @mycurrentDate AS `current_date`,
        `tn`.`start` AS `starts_on`,
        `tn`.`end` AS `ends_on`,
        `tn`.`product_id` AS `Product_id`,
        IF(`tn`.`end` >= @mycurrentDate, DATEDIFF(`tn`.`end`, @mycurrentDate), 0) AS `days_remaining`
    FROM `booking` AS `tn`
)tn LEFT JOIN product p ON tn.`Product_id` = p.product_id AND tn.`days_remaining` = 0
-- WHERE tn.days_remaining = 0
  

演示: http://sqlfiddle.com/#!9/5bf34/18/1

<强>解释

我将您的查询包含在FROMLEFT JOIN的结果中,表格product位于其product_id上。另外,LEFT JOIN仅在days_remaining为零时才匹配。

如果您要过滤结果以仅显示product_name的记录,则必须在此解决方案的末尾添加以下行:WHERE tn.days_remaining = 0

答案 1 :(得分:0)

你可以在这样的地方做到这一点:

SELECT 
    tn.id, 
    p.product_name,
    @mycurrentDate AS `current_date`,
    `tn`.`start` AS `starts_on`,
    `tn`.`end` AS `ends_on`,
    `tn`.`product_id` AS `Product_id`
FROM `booking` AS `tn`
JOIN product as `p` on p.product_id = tn.product_id
WHERE IF(`tn`.`end` >= @mycurrentDate,
         DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends
         0 #the event has already passed
    ) = 0

小提琴:http://sqlfiddle.com/#!9/5bf34/25

编辑:不完全是第二个查询,而是您要查找的结果。

答案 2 :(得分:0)

使用您自己的查询,我展开了它:

public function articleAction()
    $repository = $this->getDoctrine()->getRepository('appBundle:Article');
    $query = $repository->createQueryBuilder('a')
            ->select('a.id','a.title','a.num')
            ->where("a.num AS Max(a.num)")
            ->getQuery()
            ;
            $article = $query->getResult();
    return $this->render('appBundle:articles:article.html.twig', array('article'=>$article));
}