I have three tables I’m pulling from currently. reports, berries and melons. I set up my query like this, and it gets me exactly what I want.
SELECT
rpt.*,
ber.shipper, ber.po, ber.commodity, ber.label
FROM reports rpt
LEFT JOIN berries ber ON rpt.inspection_number = ber.report_key
LEFT JOIN melons mel ON rpt.inspection_number = mel.report_key
WHERE rpt.status='1' OR rpt.status='0'
ORDER BY rpt.inspection_number DESC
I’m getting my expected return which is
key | role | region | inspection_type | inspection_number | shipper | po | commodity | label
3 | NULL | Seattle | melons | 5555 | Shipper1 | PO2 | Commodity2 | Label2
2 | NULL | Seattle | berries | 1023 | Shipper1 | PO1 | Commodity1 | Label1
If though I remove LEFT JOIN melons mel ON rpt.inspection_number = mel.report_key from my statement I get the exact same thing…. I never mentioned melons??
If I revise and use JOIN instead for berries
SELECT
rpt.*,
ber.shipper, ber.po, ber.commodity, ber.label
FROM reports rpt
JOIN berries ber ON rpt.inspection_number = ber.report_key
WHERE rpt.status='1' OR rpt.status='0'
ORDER BY rpt.inspection_number DESC
It produces what I expected it should!
key | role | region | inspection_type | inspection_number | shipper | po | commodity | label
2 | NULL | Seattle | berries | 1023 | Shipper1 | PO1 | Commodity1 | Label1
But trying to revise my SQL statement like so….
SELECT
rpt.*,
ber.shipper, ber.po, ber.commodity, ber.label
mel.shipper, mel.po, mel.commodity, mel.label
FROM reports rpt
JOIN berries ber ON rpt.inspection_number = ber.report_key
JOIN melons mel ON rpt.inspection_number = mel.report_key
WHERE rpt.status='1' OR rpt.status='0'
ORDER BY rpt.inspection_number DESC
Nets me….
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0011 sec )
Gives me the big middle finger. What the hell? Can someone explain what I’m evidently doing wrong, and how to fix it?
It’s not so complex. Your first query, you’re joining against mel but never doing anything with it, so you’re only getting ber’s data. Your last query is closer, but because you’re inner joining against berries and melons and you don’t have any reports that are both, you get no results. But the answer is closer to what you’re doing in the second query, and I think what you want is this:
This query says, give me rows where there’s a join in berries or melons, but for the columns they have in common, give me whichever one exists. We’re taking ber first for no particular reason.
Assuming these two tables are mutually exclusive, I think this does what you want.
Edit: building on what @MarcusAdams points out below, this could be rewritten to use a
UNIONif there are an obnoxious number of fruit tables:This query will give you something handy you can use as a subquery (or view) later on. You can also hard-code an origin name like so:
Then to use this in your original query, you would embed it like so: