简体   繁体   中英

MySQL Join three tables and display 0 if null

I have three tables:

person_table

id| name | gender

1 | Joe | male

2 | Jane |female

3 | Janet | female

4| Jay | male etc...


product_table

id| name

1 | magazine

2 | book

3 |paper

4 | novel

etc...


**person_product

person_id| product_id | quantity

1 | 1 | 1

1 | 3 | 3

2 | 3 | 1

4 | 4 | 2

etc...


I have tried to make a query that will return a table like this: person_id| person_name | product_name| quantity but i can't make it so that if lets say John has no books, it should display (johns id) John|book|0 instead of just skipping this line. Where did i go wrong? here is what i managed to come up with:

SELECT p.*, f.name, l.quantity 
FROM person_product AS l 
INNER JOIN people_table AS p ON l.person_id=p.id 
INNER JOIN product_table AS f ON l.product_id=f.id
ORDER BY id`

It seems that you're generating a report of all people, against all products with the relevant quantity; on a large data set this could take a while as you're not specifically joining product to person for anything other than quantity:

SELECT
p.id,
p.name,
p.gender,
f.name,
IFNULL(l.quantity,0) AS quantity

FROM person_table AS p

JOIN product_table AS f

LEFT JOIN person_product AS l
    ON l.person_id = p.id
    AND l.product_id = f.id

ORDER BY p.id, f.name

Which results in:

在此输入图像描述

Is that more-or-less what you're after?

you need to start with people_table than using left join you need to bring other table data.

as you need 0 value if null than you can use function IFNULL

SELECT p.*, f.name, IFNULL(l.quantity,0)
FROM people_table AS p
LEFT JOIN  person_product AS l  ON l.person_id=p.id
LEFT JOIN product_table AS f ON l.product_id=f.id
ORDER BY p.id

if has no book shouldn't appear in the table , try this (easy to understand) :

SELECT NAME
    ,'0'
    ,'0'
FROM person_table
WHERE id NOT IN (
        SELECT person_id
        FROM person_product
        )

UNION

SELECT person_id
    ,product_id
    ,quantity
FROM person_product;

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