简体   繁体   English

mysql如果满足条件,则执行join,否​​则不执行

[英]mysql if condition met then execute join otherwise not

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. 我只想在if语句为true的条件下执行join语句,否则不要执行join并让其余的查询执行。

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 如果t.video_id!=''然后运行join语句

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

a common WHERE Statement in whole query 整个查询中的通用WHERE语句

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 如果t.video_id!=''则WHERE语句也需要此条件

pv.status=3

Basically if 'postdata' table contain field 'video_id' which contain id of videos. 基本上,如果“ postdata”表包含字段“ video_id”,其中包含视频的ID。 And 'processes' table contain these video_id as well. 并且“进程”表也包含这些video_id。 So if postdata.video_id is not empty then execute join statement to check if video_id is processes table contain status=3. 因此,如果postdata.video_id不为空,则执行join语句以检查video_id是否为进程表中包含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. (如果status = 3仅获取视频记录),否则,如果postdata.video_id为空,则在不使用join语句和通用Where语句的情况下执行查询。

Please help. 请帮忙。

I think you should use left join every time and add pv.status=3 to join conditions, like: 我认为您应该每次使用左连接并添加pv.status=3来加入条件,例如:

<?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... 和mysql将为您解决所有问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM