Combine Two Queries into One? - php

I have a MySQL query that selects all audioids from a certain user in a subscribe table.
I then have another query which takes this list of audioids and matches them against a field called opids in a table called audioposts. It then selects the titles from that audioposts table and joins the users from a users table at the userid.
Is there a way I can turn these two queries into one query?
query1 = "SELECT audioid FROM subscribe WHERE userid = $userid";
query2 = "SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio";
Here is the current two query code which I'd like to replace with one query. I've not yet translated this into prepared statements as it's easier for me to visualize it the old-fashioned way. Plus I'll be converting this into NodejS eventually anyway;
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}

Just add another join with subscribe.
SELECT ap.audioid, ap.title, us.name
FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN subscribe s ON s.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE s.userid = $userid AND ap.opid <> '0'

Related

SQL query to fetch data of a particular user, from three tables

First is a user table, second a places table and third a favorites table (having two fk, one from user and another from places). I want to get all the favorite places of one user, how do I do that?
I tried to play around with joins but what I don't know is how to get data of a particular user.
$qry =
"SELECT places.place_id , places.db_image ,places.description from places
inner join favorites on places.place_id = favorites.place_id
inner join user on user.id = favorites.user_id
";
$query=mysqli_query($con ,$qry);
$return_arr = array();
$sql = sprintf(
'SELECT
p.place_id,
p.db_image,
p.description
FROM
places p INNER JOIN
favorites f ON p.place_id = f.place_id INNER JOIN
user u ON u.id = f.user_id
WHERE
u.id = %d'
, $userId);
or if you want simply select all columns from places
SELECT
p.*
FROM
places p INNER JOIN
favorites f ON p.place_id = f.place_id INNER JOIN
user u ON u.id = f.user_id
WHERE
u.id = %d
It is better to use prepared statements, but if you are not familiar with them, this is good enough.

get in single MySql query from this four

want to combine this 4 query in single mysql query and my current query is
$sql1 = "SELECT * FROM projectFiles pf
INNER JOIN projectFileFolders pff ON pf.folderID = pff.folderID
WHERE pff.projectID = '".$row['projectID']."' AND folderType=3"
$sql2 = "SELECT * FROM projectFiles pf
INNER JOIN projectProducts pp ON pf.fileID = pp.fileID
WHERE pp.projectID = '".$row['projectID']."'"
$sql3 = "SELECT * FROM projectFiles pf
INNER JOIN projectMaintenance pm ON pf.fileID = pm.fileID
WHERE pm.projectID = '".$row['projectID']."' "
$sql4 = "SELECT * FROM projectFiles pf
INNER JOIN projectServices ps ON pf.fileID = ps.fileID
WHERE ps.projectID = '".$row['projectID']."' "
If I understand your requirement correctly, you have four tables, and you want to include any records from those tables whose projectID matches the one in your provided $row['projectID'] field. If so, you can simply combine all your queries like this:
$sqlWhatever =
"SELECT * FROM projectFiles pf
INNER JOIN projectFileFolders pff ON pf.folderID = pff.folderID
INNER JOIN projectProducts pp ON pf.fileID = pp.fileID
INNER JOIN projectMaintenance pm ON pf.fileID = pm.fileID
INNER JOIN projectServices ps ON pf.fileID = ps.fileID
WHERE pff.projectID = '".$row['projectID']."' AND folderType=3
OR pp.projectID = '".$row['projectID']."'
OR pm.projectID = '".$row['projectID']."'
OR ps.projectID = '".$row['projectID']."' "
Now, you haven't said whether each of the four tables has the same fileID's or not. If they do not, then change your INNER join to a LEFT join, or you'll only get records that have a common fileID in each of the four tables.

Sql Query Retrieving Data from Multiple Tables

i want to retrieve Data form 3 specifies Tables namely
UserDetail(Fname,Lname,User_id),
Movies(Movie_id,MovieName)
UserLikedMovies(User_id,Movie_id)
such that when a user enter a specific Movie_id then Userid Fname Lname form User detail MovieName from Movies,,
Here is what i tried
SELECT UserDetail.FName
FROM
UserDetail UserDetail
INNER JOIN
UserLikedMovies UserLikedMovies
ON
UserDetail.User_id = UserLikedMovies.User_id
INNER JOIN
(
SELECT
Movies.MovieName,
Movies.Movie_id
FROM
Movies Movies
INNER JOIN
UserLikedMovies UserLikedMovies
ON
Movies.Movie_id = UserLikedMovies.Movie_id
INNER JOIN
UserDetail UserDetail
ON
UserLikedMovies.User_id = UserDetail.User_id
WHERE
Movies.Movie_id IN ( Select UserLikedMovies.Movie_id from UserLikedMovies where UserLikedMovies.Movie_id = 4)
) as ABC
ON UserLikedMovies.Movie_id = ABC.Movie_id
AND Movies.Movie_id = ABC.Movie_id
Suppose movie_id is 9, then query is below.
SELECT User.Fname, User.Lname, (SELECT MovieName FROM Movies WHERE Movie_id = 9) AS MovieName
FROM UserDetail User
INNER JOIN UserLikedMovies Like
ON User.User_id = Like.User_id
WHERE Like.Movie_id = 9;
It is pretty simple query:
SELECT ud.`User_id`, ud.`Fname`, ud.`Lname`, m.`MovieName`
FROM `Movies` m
RIGHT JOIN `UserLikedMovies` ulm ON ulm.`Movie_id` = m.`Movie_id`
LEFT JOIN `UserDetail` ud ON ud.`User_id` = ulm.`User_id`
WHERE m.`Movie_id` = 4
I do not know why you are using fearful sub-queries for this simple task.

How to make a fancy mysql join that can join three tables and detect if one table DOESNT have my item

php mysql query
I have multiple linked tables - I also have a table that only creates and entry if certian conditions exist so I would like to add that into my query to avoid having to go through thousands of query searches looking for this special case
here is my current query
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city'";
I then go through each item that was returned (in the thousands)
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$sentdata = getothertable($row['UUID']); //checks if the item is in the table
$sent = $sentdata ['senttoGarcom'];
if($sent == 0) //if it wasn't found add it to my list
{
array_push($Contracts,$row['UUID']);
}
}
instead of all that I would like to just make it one query - pseduo code something like this
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
INNER JOIN contract_sales c ON a.UUID = c.contractUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city' AND c.DOESNOTEXIST";
this way I dont have to return thousands I will only be returned the few that are not yet in the contract_sales table and I can go about my business...
Appreciate any help!
just check for NULL rows of c with a outer join
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
LEFT OUTER JOIN contract_sales c ON a.UUID = c.contractUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city' AND c.contractUUID IS NULL ";
I think this is a left outer join problem
Have a look at this example. You specifically need to have a check for a null in a column in the table which you want to find the missing row rof
mysql left outer join
Sounds like a NOT EXISTS correlated subquery is what you need:
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city'
AND NOT EXISTS (SELECT 1
FROM contract_sales c
WHERE c.contractUUID = a.UUID)";

Displaying results from multiple tables SQL/PHP

I currently have a database with 12 tables. I am doing a php query to pull the information from the database but I am not getting anything displayed. The query alone bridges all the tables starting with table schedule that have a foreign key related. Should I need to start the query from the table class and bridge with other tables?
TABLE DESIGN- PICTURE
If you like to duplicate my design- QUERY
$query = ("SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id
INNER JOIN faculty
ON faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN section
ON section.faculty_id = faculty.id
INNER JOIN class
ON class.id = section.class_id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
");
//execute query
$result = mysql_query($query);
if ($result){
$totalhours = 0;
while ($row = mysql_fetch_assoc( $result ))
{
print "<b>" . $row['class_name'] . "</b><br>";
print $row['class_caption'] . "<br>";
print $row['class_description'] . "<br>";
print $row ['class_credit_hours'] . "hrs. <br>";
print "------------------------------<br />";
$totalhours += $row['class_credit_hours'];
}
}
SQL fiddle query
SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
Right here there's a problem: you are doing a INNER JOIN using the field 'class.id' but the table 'class' isn't in either side of the JOIN. So it won't work.
The query should start like this:
SELECT class_name, class_caption, class_credit_hours, class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
And then do the JOIN with the table 'schedule' with the table it shares a common index (I guess it would be class).
The complete query should be something like this:
SELECT class.class_name, class.class_caption, class.class_credit_hours, class.class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id OR faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
INNER JOIN sched_sect_br
ON sched_sect_br.section_id = section.id
INNER JOIN schedule
ON schedule.id = sched_sect_br.schedule_id
INNER JOIN semester
ON semester.id = schedule.semester_id
INNER JOIN office_hours
ON schedule.id = office_hours.schedule_id AND faculty.id = office_hours.faculty_id
This query gets info from all the tables you have in your graph, aside from the event table, that isn't related to any other. But still this query should have more fields on the SELECT (you are only selection fields from the class table, I understand you'd want data from the other 10 tables as well), to do this simple add 'tablename.field' to the list of fields from the SELECT.

Categories