Summary
So I have 3 tables, which I have screenshots below. Every user will get 10 slides by default when they sign up, so that information is in the “slides” table. The template_id is just another table I have which is identical to the custom_slides table except there are 10 pre-made slides which are default slides, so if I ever want to update the page name of a default slide, I just do it once in that template table.
If the slide is a custom slide, then template_id will be NULL just like you see for Slide 11, and slide 11 gets put in the custom_slides table.
What I need
So I need help writing a query to get some information. I want to grab the slide_id, the sort_order, and the page_name for a certain user.
So far I have the following:
SELECT slide_id, sort_order FROM `user_slides` WHERE user_id = 1
Now I need to grab the page_name but I need to run a separate query.
- Check slide_id on the slides table and see if template_id is NULL or has a value.
- if it has a value then it is a default slide, so if the template_id is 3 then I need to run a query to get the page_name from the templates table where template_id = 3
- if template_id is NULL then I need to run a query to look for the page_name in custom_slides table where slide_id = whatever slide id.
I’m not too experienced yet with running multiple queries and UNION and all of that, so if someone could help me get started in creating this query I would really appreciate it.
Table Previews
user_slides

slides

custom_slides

I believe this query should fetch the data you want:
Clarification:
This is basically the select query you posted with a few joins.
First the
slidestable is joined matching the slide_id.Then the
templatestable is joined, the outer join makes sure the rows where template_id is NULL are still included. And last thecustom_slidestable is joined but only if template_id is NULL. then usingCOALESCEwe select the page name from eithercustom_slidesortemplates.