简体   繁体   中英

MySql join statement with all rows in left table

Assume I have three tables:

1. Fields
ID
NAME

2. DATA
ID
f_id
p_id
data

3. PROJECT
ID

And I need to select all the rows from fields table every time with different data (depend on what project I need) So every time I will have all the rows of fields and if the project X does not have data for some field its will return empty row.

I tried the following SQL statements:

SELECT * FROM field as f 
left data as d on f.ID = d.f_id
WHERE d.p_id = 'X'

This will return only the rows that project X has some data and will not return empty rows if there is no data.

I also tried:

SELECT * FROM field as f 
left join data as d on f.ID = d.f_id
left join project as p on p.ID = d.p_id

This will returns all the rows from fields but will also return other projects data, and if Ill add Where statement its will not return empty rows if the project has no data.

I also tried:

SELECT * FROM field as f 
left join data as d on f.ID = d.f_id
left join project as p on p.ID = d.p_id
WHERE (p.ID == 'x' || p.ID is null) 

But this return field rows only if the rows are not using by other project, and if there is field that other project using it so I wont get this field. (not getting al rows from left table)

How can I select all the rows from the left table (fields) anyway, also if the project has no data?

SELECT * 
FROM Fields AS F LEFT JOIN DATA AS D ON 
     F.ID=D.ID LEFT JOIN PROJECT AS P ON F.ID=P.ID
SELECT * FROM field as f 
left join data as d on f.ID = d.f_id
WHERE ISNULL(d.p_id,'X') = 'X'

SELECT * FROM field as f 
left data as d on f.ID = d.f_id
WHERE (d.p_id = 'X' or d.p_id is null)

Okay, let me see, first I would do this:

    SELECT F.* FROM field F 
    LEFT data D ON F.id = D.f_id
    WHERE D.p_id = 'X';

Because you said you only want the data from the table field, right? If you leave the * over there without the table prefix it will give you every data you have on every table you have on the joins and you might have the ambiguous error because of the columns ID you have on every table.

Another thing, I took the AS out because it usually applies better for putting aliases on column names such as:

    "COUNT(ID) AS COUNTER"

And I'm sorry, but the way I see it, the problem might be the solution. Why do you want to select empty rows? Do you mean columns or rows?

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