I’m trying this query but it wont work how I thought it should lol
SELECT minerals.mineral, bank.amount, members.credits AS cash FROM minerals INNER JOIN members RIGHT JOIN bank ON bank.minerID = minerals.id WHERE userid LIKE 1
There are 10 minerals and the bank contains the amount of each for each user. But the user 1 used in the query only have 9 out of 10. This query only returns a list of 9 and not 10.
CREATE TABLE minerals( idint(11) NOT NULL AUTO_INCREMENT, mineralvarchar(32) NOT NULL, priceint(11) NOT NULL, description text NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
Bank
CREATE TABLE bank( idint(11) NOT NULL AUTO_INCREMENT, minerIDint(11) NOT NULL, userIDint(11) NOT NULL, amount bigint(20) NOT NULL, PRIMARY KEY (id), UNIQUE KEY id (id) ) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=utf8
If you have a condition which checks for a value on the table you’ve right joined, it becomes an inner join.
If you want to find all the minerals as related to user 1, then you need to reverse the starting point on the query. I also noticed you don’t have any criteria on your join to the members table - how does this one match up?
SELECT minerals.mineral
, bank.amount
, members.credits AS cash
FROM bank
INNER JOIN members ON ??? = ???
LEFT JOIN minerals ON bank.minerID = minerals.id
WHERE userid = 1 -- the like is not appropriate it's a specific value
Im adding the members table cause I need to print the amount of credits the user has. The rest will print the amount he has of each mineral. With the right join I would like to include minerals that the user dont have as well.
So it would look something like user has 10 credits, 5 gold, 2 silver, 0 bronze etc …
That’s fine, but the point is you’re not tying the tables together, so you’ll get ALL of the records on the members table instead of what just matches. You need an ON condition in there (something like ON bank.userid = members.id)
SELECT minerals.mineral
, bank.amount
, members.credits AS cash
FROM members
LEFT OUTER
JOIN bank
ON bank.userID = members.userid
LEFT OUTER
JOIN minerals
ON minerals.id = bank.minerID
WHERE members.userid = 1
Thanks, I didn’t know I added like you said. Only the ones the user has. So when I do an inner join or any kind of join I need an ON statement too right ?
SELECT minerals.mineral
, bank.amount
, members.credits AS cash
FROM bank
INNER JOIN members ON members.id = bank.userID
RIGHT JOIN minerals ON bank.minerID = minerals.id
WHERE userid = 1
SELECT minerals.mineral
, bank.amount
, members.credits AS cash
FROM minerals
LEFT OUTER
JOIN bank
ON bank.minerID = minerals.id
AND bank.userID = 1
LEFT OUTER
JOIN members
ON members.userid = bank.userID