PHP MySQL Display Joined and non- Joined Records - php

I am having a problem with not been able to display all records from table1.
I have 2 tables.
Table 1 and 2 and I want to display all the records from table 1 (Even if some records donly exists on table1 and no reference in table2)
This is what I am trying and I have 2 recording in Table1 but it's only displaying 1.
1 record is joined by the name_id on table1 and table2 and the other record only exists on table1 BUT I need to display both.
Here is the query:
$query = mysql_query("SELECT
table1.name_id,
table2.name_id,
FROM `table1`
LEFT JOIN `table2` ON table1.name_id=table2.name_id
");
How can I get it so it will display all the records from table1 (The one's that are join and the ones that are not too) ?

you can use "JOIN" to fetch data from both table as
$query = mysql_query("SELECT table1.name_id, table2.name_id FROM `table1` JOIN `table2` ON `table1`.`name_id`=`table2`.`name_id` ");

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

Getting data from one table based on results of another SQL PHP

I know this involves JOINS but I can't seem to find a working solution to what I'm trying to do.
I have 2 custom tables :
table1 | table2
---------------------
id id
uid uid
track_id track_id
date date
art active
info
blah
blah2
First I want to select everything WHERE uid=55 AND active=1 from table2 :
$tracks = $wpdb->get_results( "SELECT * FROM table2 WHERE uid = 55 AND active = 1");
And then match the track_id from table2 with results from table1 so I can traverse the table1 data.
I know I can do it like this :
foreach( $tracks as $track ) {
$this_track = $track->track_id;
$results = $wpdb->get_results( "SELECT * FROM table1 WHERE track_id = $this_track");
// Do stuff here
}
But this is the part where it gets tricky...
I then want to ORDER the $results from table1 by date DESC from table2
And this is where I'm lost...
Effectively I want (pseudo code) :
$results = $wpdb->get_results( "SELECT * FROM table1 WHERE track_id = $this_track" ORDER BY date DESC FROM table2);
As well as that last bit, I know I can do this entire routine with JOINS to keep this all in one query and make it way more efficient but I just don't know how.
So just to be clear, my overall routine should be like this :
Get all instances of track_id from table2 where user_id=55 and active=1, then use those results to match the track_id to every result in table1 with the same track_id and then sort the results by date back over from table2
Psuedo code, I know it contains nonsense :
$finalresults = $wpdb->get_results( "SELECT * FROM table2 where uid=55 AND active=1 THEN SELECT * FROM table1 WHERE track_id = "the track_id from the first query" THEN ORDER BY date DESC FROM table2);
Try with this query
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1 ORDER BY t2.date DESC;
Edit: Explanation of what this query is doing. and inverted the order of the tables retrieved in the query (this don't affect the final datatset, i did this to make to follow the logic of the explanation.
1.- Begin with retrieving all rows from table2 (theres is no specific reason because i used table2 over table1, I'm only following an logical order), using the criteria that you specified iud=55 and active=1
SELECT * FROM table2 WHERE uid=55 AND active=1;
2.- but as you said you need to expand the data retrieved in table2 with some information in table1, that's exactly what it is the directive JOIN made, and we are using INNER JOIN because this type of JOIN will show rows ONLY if data for the uid=55 is present on table1, if there is NO data for the uid=55 present on both TABLES then mysql wil show empty the recordset (0 Rows selected).
in the ON(...) part I specify which criteria mysql will use to compara both tables for match in this case will compare that track_id on table2 it is the same that the specified on table1, if this codition is met then mysql considers it as a match.
anly for convenience and because i'm adding a Second table i gave an Alias to each one t1 and t2.
then the query now seems like this
SELECT * FROM table2 AS t2 INNER JOIN table1 AS t1 ON(t1.track.id = t2.track_id) WHERE t2.uid=55 AND t2.active=1;
3.- but then raise a problem, both tables has rows with the same field names, and this is something that DBMS don't like in their queries, to avoid this situation in the query i only show the fields (id, uid and track_id) from one table in this case t1 (t1.*) and only show the fields that doesn't have this problem from t2 (t2.date AS t2date, t2.active). in this way mysql won't throw any error.
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1;
4.- for the final step i specify to mysql that i want all found rows ordered descent by a field in the table2;
ORDER BY t2.date DESC;
then this criteria will be applied to the whole selected rows. and the final query has this form.
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1 ORDER BY t2.date DESC;
if is not completely clear you can ask ...

php mysql with left outer join

I have two tables in mysql table1 and table2
table1 have the following fields
Field Type
intProjectId int(11)
intSourceId int(11)
intClientId int(11)
varProject varchar(200)
fltAmount float
varAmountType varchar(50)
dtStart date
dtEnd date
And table 2 have the following fields
Field Type
intPercentageId int(11)
intProjectId int(11)
floatPaymentpercentage float
ddDate datetime
join two table with common project id.If table2 has no records with the particular project id it can joined as null..
Table 1 has project data
Table 2 has its percentage of complettion. (Each project has more than one records. )
Project Id -- common field
Iused the following query
SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.intProjectId = table2.intProjectId
GROUP BY table1.varProject ORDER BY table2.intPercentageId DESC
Here i get the output as percentage table returns the first record for each project. I need the last inserted record for the table 2.
table1 ==> project id 5
In table 2 has 3 records for project Id 5. I want to ge the last record from the table2. Now it returns the first record from table 2
How to change the query. Please help me to fix this.
Calculate the maximum record for each project in table2 and use that information to get the latest record. Here is a method that uses group by:
select t1.*
from table1 t1 join
table2 t2
on t1.intProjectId = t2.intProjectId join
(select t2.intProjectId, max(intPercentageId) as maxpi
from table2 t2
group by t2.intProjectId
) tt2
on t2.intProjectId = tt2.maxpi;
Calculate the maximum record for each project in table2 and use that information to get the latest record. Here is a method that uses group by:
select t1.*
from table1 t1 join
table2 t2
on t1.intProjectId = t2.intProjectId join
(select t2.intProjectId, max(intPercentageId) as maxpi
from table2 t2
group by t2.intProjectId
) tt2
on t2.intProjectId = tt2.maxpi;
Try this
SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.intProjectId = table2.intProjectId
GROUP BY table1.varProject HAVING MAX(table2.intPercentageId)
"Order By" runs after "Group by" has completed, that is why it is not giving the intended result. The change I have suggested will give the row from 2nd table with the highest percentage which as per the scenario should be the last row for the project.

mysql query to display data using joins?

I have two tables I want to display datas which are not in table 2 but exist in table 1 and after listing the datas.I want to add those datas in table 2.
which join shall i use?please help me with the code
You need no join at all. You want data from table1 where no entry exists in table2. So use the EXISTS clause.
select something
from table1
where not exists
(
select *
from table2
where table2.somekey = table1.somekey
);
As to the insert:
insert into table2 (column names)
select something
from table1
where not exists
(
select *
from table2
where table2.somekey = table1.somekey
);

PHP SQL Request - Query 2 tables, for results on one query

I need to query the database to pull all cars that a particular user likes.
I know that user_id is 1
Then I have 2 tables. 1 contains all the cars ... id and description and table 2 contains the likes.
Table 1 has a list if cars and these fields:
car_id
car_name,
car_description
Table 2 has what cars I like and these fields:
user_id
car_id
likes (1 or 0)
So I need to pull out only the records that user 1 likes from Table 2 but only the ones he likes
What SQL query would I need to do for that?
SELECT * FROM table1 as t0
LEFT JOIN table2 as t1 on t0.car_id = t1.car_id
WHERE t1.likes = 1
Try this
SELECT * FROM table1 as t1 LEFT JOIN table2 as t2 on t1.car_id = t2.car_id WHERE t2.user_id = $user_id
Try this query
SELECT t1.*,t2.*
FROM tbl1 t1,tbl2 t2
WHERE likes = 1 AND user_id = 1 AND t1.car_id = t2.car_id

Categories