I have a few tables in my database:
usertable:user_id (primary key),first_name,last_name,email_address.insttable:inst_id (primary key),inst_name, andtype.user_inststable:user_insts_id (primary key),user_insts_status,inst_name (foreign key)anduser_id(foreign.
key)
I’m using this on my website and i need it to display all of the entrys in the inst_name column for the inst table, but only the entrys for a certain id in the right side or else show as null. I’ve tried a few things like below:
SELECT inst.inst_name,inst.inst_id,user_insts.user_id,user_insts.inst_name
FROM inst LEFT JOIN user_insts ON inst.inst_name=user_insts.inst_name;
SELECT inst.inst_name,inst.inst_id,user_insts.user_id,user_insts.inst_name
FROM inst LEFT JOIN user_insts ON inst.inst_name=user_insts.inst_name
WHERE user_insts.user_id='11';
Any help would be greatly appreciated.
EDIT::
this is what i currently get:
inst_name inst_id user_id:
ASB 1 11
BNZ 3 11
FMG 5 11
i was hoping to be able to get something more like this:
inst_name inst_id user_id:
ASB 1 11
ANZ 2 NULL
BNZ 3 11
paymark 4 NULL
FMG 5 11
STATE 6 NULL
Do your provided queries show the following results?
inst+user_instsentries but unfiltered byuser_idinst+user_instsentries filtered byuser_idWhat’s happening in Query 2 is that the
whereclause filters the joined tables AFTER they are joined. I guess what you want to happen is to first filter the right side of the result (user_insts) by a specificuser_idlike so:Then, you want to LEFT JOIN this with all the entries in the
insttable AFTER the filter. You could use an inner view in order to filter byuser_idfirst before the actual joining to theinsttable. The resulting query should be something like this:Thinking about it more, I’m not too familiar with MySQL so I’m not sure if this alternative query is valid syntax:
… which may be simpler than an inner view.
The main point is you have to do the filtering first before joining, so that all the
inst_nameswill be displayed.