1

Hi I am stuck over a query. I want to execute join statement only when condition in if statement is true otherwise do not execute join and let the rest of query execute.

For example, my query is like this:

 SELECT `t`.`id`, `t`.`title`, `t`.`date_created`, `t`.`video_id`, `t`.`audio_id`, `t`.`created_by`, `t`.`updated`, `t`.`gamenumber`, `t`.`cat_id`, `t`.`is_deleted`, `t`.`marked_by`, `t`.`is_hidden`, `t`.`battle_type`, `t`.`media` FROM `postdata` `t`

if t.video_id != '' then run join statement

left join processes as pv on ( pv.video_id = t.video_id) 

a common WHERE Statement in whole query

cat_id IS NOT NULL and is_deleted=0 and is_hidden=0 and battle_type="public" ORDER BY date_created 

WHERE statement also requires this condition if t.video_id!='' then

pv.status=3

Basically if 'postdata' table contain field 'video_id' which contain id of videos. And 'processes' table contain these video_id as well. So if postdata.video_id is not empty then execute join statement to check if video_id is processes table contain status=3. (if status =3 only then fetch video records) otherwise if postdata.video_id is empty then execute the query without join statement and common Where Statement.

Please help.

3
  • why not just put AND t.video_id <> '' in the join predicate. you'll get null values for the rows that dont match. Commented May 27, 2015 at 13:34
  • How is this related to Yii? Commented May 28, 2015 at 7:01
  • @craafter, I have simplified the query in mysql. I am actually working on Yii and using CDbcriteria for executing this query. Commented May 29, 2015 at 2:16

1 Answer 1

0

I think you should use left join every time and add pv.status=3 to join conditions, like:

<?php

$where = [
    'is_deleted'  => 0,
    'is_hidden'   => 0,
    'battle_type' => 'public',
];
$postdata = new postdataModel;
$processes = new processesModel;
$command = $postdata->getDbConnection()->createCommand()
    ->select('t.id, t.title, t.date_created, t.video_id, t.audio_id, t.created_by, t.updated, t.gamenumber, t.cat_id, t.is_deleted, t.marked_by, t.is_hidden, t.battle_type, t.media')
    ->from('postdata AS t')
    ->leftJoin('processes AS pv', 'pv.video_id = t.video_id AND pv.status = 3')
    ->where('cat_id IS NOT NULL AND is_deleted = :is_deleted AND is_hidden = :is_hidden AND battle_type = :battle_type')
    ->order('t.date_created DESC')
;
$data = $command->queryAll();

and mysql will resolve all for you...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.