2017-11-24 2 views
0

Ich habe 2 Tabellen:Mysql Kriterien aus zwei Tabellen mit optionalen zweiten Kriterien

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 

Und ich brauche alle Datensätze aus table1 basierend auf job_id auszuwählen und alle Daten von table2 zu füllen, wenn wir die gleichen ids haben mit unser Wunsch pl_id.

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

So muss das Ergebnis

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

zu tun, dass ich mit dieser Abfrage versucht:

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

aber es gibt nur record2

Antwort

0

Sie links machen beitreten auf falsche Tabelle. Sie wollen tabelle1 Rekord p_id mit und haben auf table2

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

Das Ergebnis ist das gleiche –

+0

@ ВладимирГичев Versuche es jetzt –

0

Sie nur LEFT JOIN geben müssen kommen gelassen, aufgrund Ihrer Erkrankung Ergebnis könnte modifiziert werden,

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