简体   繁体   中英

mysql select all rows in left and let null in right table

I have two tables in MySql Database, the tables is:

在此输入图像描述

upper one table is jenis_pohon and the lower one is jtt

how to select all rows in jenis_pohon and join it with jtt with condition jtt.tahun='2016' AND jtt.koperasi_id='4'

I tried the following query:

SELECT * FROM `jenis_pohon` LEFT JOIN jtt ON jenis_pohon.jenis_pohon_id=jtt.jenis_pohon_id WHERE jtt.tahun='2016' AND jtt.koperasi_id='4'

but no luck.

basicaly I want to have 6 rows returned (this 6 rows is come from jenis_pohon ).

Try using below Query.

SELECT
    *
FROM
    `jenis_pohon`
LEFT JOIN jtt ON jenis_pohon.jenis_pohon_id = jtt.jenis_pohon_id
AND jtt.tahun = '2016'
AND jtt.koperasi_id = '4';

LIVE DEMO

OUTPUT

在此输入图像描述

Check this. Check here Demo

Table jtt with condition jtt.tahun='2016' AND jtt.koperasi_id='4' it returns only 3 records because jtt.koperasi_id='4' ave only 3 records into tabel 'jtt'

 SELECT * FROM `jenis_pohon` 
LEFT JOIN jtt ON jenis_pohon.jenis_pohon_id=jtt.jenis_pohon_id 
WHERE jtt.tahun='2016' AND jtt.koperasi_id='4';

O Table jtt with condition onlt jtt.tahun='2016'

  SELECT distinct * FROM `jenis_pohon` 
  LEFT JOIN jtt ON jenis_pohon.jenis_pohon_id=jtt.jenis_pohon_id 
   WHERE jtt.tahun='2016'

I've Created Your tables and tested it, it works. Use This query :

SELECT * FROM jenis_pohon 
LEFT JOIN jtt ON (jenis_pohon.jenis_pohon_id = jtt.jenis_pohon_id AND jtt.tahun = '2016' AND jtt.koperasi_id = '4')

Notice that using AND inside join parenthesis make your query mush faster than using WHERE.

The result is :

在此输入图像描述

You can sort it like :

SELECT * FROM jenis_pohon 
LEFT JOIN jtt ON (jenis_pohon.jenis_pohon_id = jtt.jenis_pohon_id AND jtt.tahun = '2016' AND jtt.koperasi_id = '4') 
ORDER BY jenis_pohon.jenis_pohon_id 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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