Dan Dan - 3 months ago 14
MySQL Question

Using RIGHT JOIN to match page data to the page

In my code, I am trying to join page names and page data names so that I am able to populate a web page with the data in my databases. The two tables look like the following pictures.

page_data

Table 1

pages

Table 2

So when I ran the following code in my PHP function I did not expect the echo to output

1
.

function merge_page($dbc) {
$q = "SELECT pages.page_name, page_data.section_name
FROM page_data
RIGHT JOIN 'page_data'
ON pages.id = page_data.section_page_id";

$r = mysqli_query($dbc, $q);
echo print_r($r);
return 0;
}


I expected something along the lines of

pages.page_name page_data.section_name
Welcome Section 1
Welcome Section 2
Welcome Section 3
Welcome Section 4
Welcome Section 5


I would appreciate any help in fixing this problem

Answer

I think you should use an inner join (between page_data and pages ) and not a right join between page_data and page_data

"SELECT pages.page_name, page_data.section_name 
 FROM page_data 
 INNER  JOIN 'pages' 
     ON pages.id = page_data.section_page_id";

or left join if the rows could don't match

"SELECT pages.page_name, page_data.section_name 
 FROM page_data 
 LEFT  JOIN 'pages' 
     ON pages.id = page_data.section_page_id";
Comments