mySQL JOIN on one to many - php

I have multiple tables that are linked together on the search page. They are currently queried like this:
SELECT * FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid
I have since created a new table called tripphotos with the table columns named:
tripphotoid
reportid
entryid
photoname
The issue is each entry can have more than one corresponding photo in the photo table.
I am looking to find a way to JOIN the new table to the statement above but not return several rows for each entry id.
Any ideas on how to join this table?
EDIT - I also want to just tie one image to the returned row and not all of them just so I can show the image as a thumbnail on the browse page

I normally would list every column and group by the non aggregates, but mySQL will allow this I believe; given the mySQL group by extensions; and we expect the tripReport and user_Details columns to be the same for each joined photoname.
SELECT tripReport.*, user_details.*, max(photoname) as maxPhotoPerReport
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details ON tripreportentries.userid = user_details.userid
JOIN tripphotos ON tripreportentries.reportid = tripPhotos.ReportID
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
GROUP BY ReportId
ORDER BY tripreportentryid
or we could do this using an inline view to get the max photo for each report and then join that set to your base query.
SELECT *
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
JOIN (SELECT max(photoName) as MaxPhotoPerReport, ReportID
FROM TripPhotos
GROUP BY ReportID) B
ON B.ReportID = tripReport.ReportId
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid

Related

Retrieving data from multiple tables mysql php

I have 2 tables MOVIES and SHOWS.
MOVIES tables contains:
id, name, image, description.
SHOWS table contains:
id, movieid, description.
I'm executing mysql statement to retrieve records from SHOWS table, i'm getting all the records normally. Again I'm executing another mysql statement to get image from MOVIES table based on movies table id which i'm getting from first query.
Is there any simple way to retrieve all the records from SHOWS table along with movie image?
These are my queries:
$qry1 = mysql_query("SELECT * FROM shows WHERE id='1'");
$res = mysql_fetch_array($qry1);
$movieid = $res['movieid'];
$qry2 = mysql_query("SELECT image FROM movies WHERE id='$movieid'");
SELECT t1.id, t1.movieid, t1.description, t2.image FROM SHOWS as t1
INNER JOIN
MOVIES as t2 ON t1.id = t2.id
Some sql join docs
or you can try this, i was not sure witch id is from where:
SELECT id, movieid, description, image FROM SHOWS
INNER JOIN MOVIES
ON id = movieid
Some foreign key docs
Here I am writing with out join you can all so use nested select queries
select movies.image from movies where movies.id in(Select shows.movieid form shows where shows.id= 1);
You can retrieve data from multiple tables from one server at the same time. There is a lot of ways to achieve this operation which is called join. One of the possibility would be the LEFT JOIN like this:
SELECT t1.field1, t1.field2,..., t2.field1, t2.field2, ..., t2.fieldn
FROM table1 AS t2
LEFT JOIN talble2 AS t2 ON t2.some_field = t1.anothed_filed
WHERE some_condition
In you case:
SELECT s.*, m.image
FROM SHOWS AS s
LEFT JOIN movies AS m ON s.movieid = m.id
WHERE some_condition
for more info see the documentation on https://dev.mysql.com/doc/refman/5.7/en/join.html

How to JOIN 2 tables on mySql?

I have two tables: publick_feed and users
I want to SELECT all from public_feed and also SELECT a three columns from users whose id is the same of user_id in public_feed
and assign the rows returned from public_feed to the column in users table ( correspondent)
I try this:
<?php
$sql = "
SELECT * FROM public_feed
WHERE user_id IN
(SELECT id FROM users) AND
(SELECT Firstname,Lastname,Avatar FROM users WHERE id IN(SELECT user_id FROM public_feed))
";
$query = mysqli_query($dbc_conn,$sql);
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
//echo rows with correspondent details from the users table
echo $row['user_id'];
}
}
<?
Please any help will be much appreciated.
Thank you.
Or version with left join in case if there is no user in public_feed, and you still want to fetch user data
SELECT
u.*, f.*
FROM
public_feed f LEFT JOIN
users u ON f.user_id = u.id;
Because author asked for explanation, here it is:
First we are going to use table name alias to make query shorter
public_feed f
and
users u
we are saying that want to refer to tables with an alias. Of course * means that we want to select all columns
SELECT users.*, public_feed.*
is equal to
SELECT u.*, f.*
Of course you can use any other letters as an alias
Next we are saying that public_feed.user_id must be equal to users.id. But when public feed entry does not exists just display columns with null values. This is why we are using LEFT JOIN instead of INNER JOIN. In general JOINS are used to fetch related data from more than one related tables.
ON keyword is saying values from which columns in the tables must be equal to satisfy the request
I think doing a join would be cleaner than using a complicated subquery:
SELECT u.Firstname,
u.Lastname,
u.Avatar,
COALESCE(pf.User_id, 'NA'),
COALESCE(pf.Post, 'NA'),
COALESCE(pf.Date, 'NA')
FROM users u
LEFT JOIN public_feed pf
ON u.Id = pf.User_id
I chose a LEFT JOIN of users against public_feed on the assumption that every feed will have an entry in the users table, but not necessarily vice-versa. For those users who have no feed entries, NA would appear in those columns and that user would appear in only a single record.

display data together from 2 different SQL table

I need to display details from 2 different tables
Table 1- user table
Table 2-bicycle table
I can show a list of users and bicycle.
But can't show a list that show which bicycle belongs to who.
Bicycle table,
user table
You need to use a LEFT JOIN. The query below will connect your user table to your bicycle table based on the userIDand return all of the bicycle and user fields
SELECT b.*, u.*
FROM registered_users u
LEFT JOIN registered_bicycle b ON (u.userID = b.userID)
If you want specific bicycle fields just prefix them with b. Example:
SELECT b.brand, b.model, b.color...
Click on SQL tab and type this:
SELECT * FROM `registered_bicycle` JOIN `registered_users` ON `registered_users`.`userID` = `registered_bicycle`.`userID`
and run it
You have to make a foreign key from user_table to bicycle_table like this.
user_table has user_id = user_1,name=John Richard
bicycle_table has user_id = user_1,description = Bicycle1
to fetch the data:
select a.user_id, a.name,b.description from
(select user_id, name from user_table) as a
left join
(select user_id,description from bicycle_table) as b
on a.user_id = b.user_id

Querying comma separated field?

I am trying to output a select dropdown options based on a comma separated field where if the user has been assigned an ID of 1 and 2 for example then I want to output the locations id has 1 and 2:
Users table:
id (which equals 1) and usergrouplocid which is a text field with (1,2)
Location Table:
id which auto_increment and a loc_id see iamge below:
My query is as follows:
$query = "SELECT room_location.*, client_room.*, users.* FROM room_location INNER JOIN client_room ON room_location.user_loc_id = client_room.id INNER JOIN users ON room_location.user_loc_id = users.userGroupLocID WHERE 1 IN (userGroupLocID) ORDER BY room_location.location";
The query above works fine but it only outputs where the id of 1 exists in usergrouplocid, so how do I get the query to find if 1, 2, 3 or 4 etc is in the usergrouplocid.
Just in case you really need it sorted now without redesigning your database (which I would)...
$ids = array(1,2,4);
$query = "SELECT room_location.*, client_room.*, users.* FROM room_location INNER JOIN client_room ON room_location.user_loc_id = client_room.id INNER JOIN users ON room_location.user_loc_id = users.userGroupLocID WHERE userGroupLocID REGEXP '(^|,)(".implode('|',$ids).")(,|$)' ORDER BY room_location.location";

Inner join 2 tables with same column names

I'm working on displaying the achievements from my minecraft server on my website.
But I can't get it to work.
function achievements() {
global $id;
$sql="SELECT * FROM achievements
INNER JOIN stats ON achievements.type=stats.type
INNER JOIN stats ON achievements.block=stats.block
INNER JOIN stats ON achievements.data=stats.data
INNER JOIN stats ON achievements.value=stats.value
WHERE player_id = $id";
$result=mysql_query($sql) or die(mysql_error());
$rows=mysql_fetch_array($result);
}
Will I be able to use $rows['achievements.type']; and $rows['stats.type']; to get the column "type" from the selected table, or is there a another way to do it?
The column and table names are defined by the plugin I use, so the names can't be changed.
the reason why it is not working is because (in my own opinion) the server is a little confused on where how it will handle the columns names properly. In order it to work, add an alias on every table that has the same name that you want to join as well as the columns, eg
SELECT achievements.*,
a.Name as TypeName,
b.Name AS BlockName,
c.Name as DataName,
d.Name AS ValueName
FROM achievements
INNER JOIN stats a ON achievements.type = a.type
INNER JOIN stats b ON achievements.block = b.block
INNER JOIN stats c ON achievements.data = c.data
INNER JOIN stats d ON achievements.value = d.value
WHERE player_id = $id
assuming you want to get the names for every specific columns.
Give the columns you want to have while you SELECT them an alias as example:
SELECT `achievements`.`type` AS `Achieve-Type`
FROM `achievements`
Now you can get the values like this: $rows['Achieve-Type'];
It's easier to alias the table names with...
SELECT * FROM achievements AS ac INNER JOIN stats as st
You could even alias the results if you wish so they are more distinguishable when you select them from $rows

Categories