简体   繁体   English

MySQL加入三个表,如果为null则显示0

[英]MySQL Join three tables and display 0 if null

I have three tables: 我有三张桌子:

person_table person_table

id| ID | name | 名字| gender 性别

1 | 1 | Joe | 乔| male

2 | 2 | Jane |female 简|女

3 | 3 | Janet | 珍妮特| female

4| 4 | Jay | 杰伊| male etc... 男等...


product_table product_table

id| ID | name 名称

1 | 1 | magazine 杂志

2 | 2 | book

3 |paper 3 |纸

4 | 4 | novel 小说

etc... 等等...


**person_product ** person_product

person_id| 为person_id | product_id | product_id | quantity 数量

1 | 1 | 1 | 1 | 1 1

1 | 1 | 3 | 3 | 3 3

2 | 2 | 3 | 3 | 1 1

4 | 4 | 4 | 4 | 2 2

etc... 等等...


I have tried to make a query that will return a table like this: person_id| 我试图创建一个返回如下表的查询:person_id | person_name | person_name | product_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. 数量,但我不能这样,如果让我们说约翰没有书,它应该显示(johns id)约翰|书| 0而不是只是跳过这一行。 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. 你需要从people_table开始,而不是使用左连接,你需要带来其他表数据。

as you need 0 value if null than you can use function IFNULL 如果你需要0值,你可以使用函数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;

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

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