简体   繁体   English

SQL从两个表中选择,如果WHERE子句为false,则为列获取空值

[英]SQL Select from two tables, get null values for columns if WHERE clause is false

http://sqlfiddle.com/#!9/cfd41ef/1 http://sqlfiddle.com/#!9/cfd41ef/1

I want to get every row from table person and if the clause WHERE is false I want to get null values. 我想从table person获取每一行,如果WHERE为false,我想得到null值。 Is there a way to do this? 有没有办法做到这一点? Thanks in advance. 提前致谢。

CREATE TABLE `pet` (
    `owner_id` INT(11) NULL DEFAULT NULL,
    `pet_type` ENUM('DOG','CAT') NULL DEFAULT NULL,
    `pet_name` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

CREATE TABLE `person` (
    `id` INT(11) NULL DEFAULT NULL,
    `first_name` VARCHAR(50) NULL DEFAULT NULL,
    `last_name` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

INSERT INTO `person` (`id`, `first_name`, `last_name`) VALUES
    (1, 'qwe', 'asd'),
    (2, 'asd', 'fgh'),
    (3, 'zxc', 'vbn');

INSERT INTO `pet` (`owner_id`, `pet_type`, `pet_name`) VALUES
    (1, 'DOG', 'rex');

SELECT person.*, pet.pet_name FROM person LEFT JOIN pet ON person.id = pet.owner_id WHERE pet.pet_type = 'DOG'

Thank you Lukasz Szozda and Yogesh Sharma for your answer moving the condition to ON does what I wanted 感谢Lukasz Szozda和Yogesh Sharma的回答,将条件转移到ON做我想要的

You could move condition to ON : 您可以将条件移至ON

SELECT person.*, pet.pet_name 
FROM person 
LEFT JOIN pet 
  ON person.id = pet.owner_id
 AND pet.pet_type = 'DOG';

SQLFiddle Demo SQLFiddle演示

Move to ON clause instead of going with where clause : 移动到ON子句而不是使用where子句:

SELECT person.*, pet.pet_name 
FROM person LEFT JOIN 
     pet 
     ON person.id = pet.owner_id and pet.pet_type = 'DOG';

You where clause turns into inner join which is the problem. where子句变成inner join ,这是问题所在。

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

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