两个表中的Mysql条件,带有可选的第二个条件

时间:2017-11-24 14:51:17

标签: mysql

我有两张桌子:

CREATE TABLE `table1` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `job_id` BIGINT(20) NOT NULL DEFAULT '0',
    `contact_name` VARCHAR(100) NULL DEFAULT NULL,
    `email` VARCHAR(100) NULL DEFAULT NULL,
    `phone` VARCHAR(50) NULL DEFAULT NULL,
    `title` VARCHAR(100) NULL DEFAULT NULL,
    `is_approve` TINYINT(2) NOT NULL DEFAULT '0',
    `is_default_contact` TINYINT(2) NOT NULL DEFAULT '0',
    `is_original_contact` TINYINT(2) NOT NULL DEFAULT '0',
    `signer` TINYINT(2) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1
;

CREATE TABLE `table2` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `contact_id` BIGINT(20) NULL DEFAULT '0',
    `signature_owner` VARCHAR(50) NULL DEFAULT NULL,
    `pl_id` BIGINT(20) NOT NULL DEFAULT '0',
    `sign_date` DATE NULL DEFAULT NULL,
    `authorization_sign_date` DATE NULL DEFAULT NULL,
    `sign_tag_file_name` VARCHAR(50) NULL DEFAULT NULL,
    `authorization_file_name` VARCHAR(50) NULL DEFAULT NULL,
    `signature_note` VARCHAR(250) NULL DEFAULT NULL,
    `authorization_signature_note` VARCHAR(100) NULL DEFAULT NULL,
    `signature_owner_email` VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1
;

where table1.id = table2.contact.id

我需要根据table1选择job_id的所有记录,并填写table2的所有数据,如果我们有ids我们想要的pl_id }}

Example:
In table1 are 3 records with job_id=1:
record1
record2
record3
In table2 is only record2 with pl_id=1

所以结果必须是

record1 + empty feilds from table2
record2 + pupulated all the fields from table2
record3 + empty feilds from table2

为此我尝试使用此查询:

SELECT *
FROM table2 s
LEFT JOIN table1 p ON s.contact_id=p.id
WHERE p.job_id=1605 and s.pl_id=5150

但它只返回record2

2 个答案:

答案 0 :(得分:0)

你正在左边加入错误的桌子。你想要table1记录有p_id并在table2上做左连接

SELECT *
FROM table1 p
LEFT JOIN table2 s ON s.contact_id=p.id
WHERE p.job_id=1605

答案 1 :(得分:0)

您只需要提供左连接,因为您的条件结果可能会被修改,

SELECT *
FROM table1 p
LEFT JOIN table2 s ON s.contact_id=p.id