I'm trying to join two tables on their id and then populate an empty array with key - values. table2 has an additional city_name column which I'd like to use.
However, after joining the two tables on their id with INNER JOIN, I cannot seem to access the city_name value from the second table (but getting the values from the first table works fine).
Here's my code:
$city_list = array();
$i = 0;
$q = "SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.city_id";
$res = $mysql_query($q);
while($row = mysql_fetch_assoc($res) {
$city_list[$i]['id'] = $row['id']; // returns the id from table1, which is also identical to the city_id from table2
$city_list[$i]['population'] = $row['city_population']; // returns the city_population value from table1
$city_list[$i]['name'] = $row['city_name']; // returns null, even though the value exists in table2
$i++;
}
When printing the $city_list, I get the appropriate id and population values, but the name key has a value of null, even though I have city names in table2.
Just select the columns you really need.
SELECT table1.id, table1.city_population, table2.city_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
You could select the column names using an alias so that you can access both as you want. eg, change query to something like:
SELECT *, table2.user_name as table2_user_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
Preferably you shouldn't use * if you don't need all the data. It tends to lead to more bugs & more difficult maintenance.
Related
PHP
Tables are:
I have 2 tables, one of trips and the other is key table (index,type)
I want to receive all the names of the trips that the index of the trip type is 1 (output = Alexander)
I receive into variable "$Trip_Type" the user's choice and in addition I need to add to the query another condition of variable $Trip_Population, that has a key table for his values named "Population". How can I combine this in the query?
"Population" is a key table like "Types": 1. index, 2. Type. In addition there is a column "Population_Type" in table Trips. I need all in 1 query
I have this query and I need to add for this the Population condition:
$query = "SELECT trips.Trip_Num
FROM trips JOIN trip_types ON trips.Trip_Type = trip_types.Type
WHERE trip_types.type = " . $Trip_Type;
select t1.name
from trips t1
inner join types t2 on t1.type =t2.type
$sql=
"SELECT t.name
from trips t
JOIN types ty ON t.type = ty.type
WHERE ty.type = " . $Trip_Type;
SELECT a.name
from trips a
JOIN types b ON t.type = a.type
WHERE b.type ='$Trip_Type'
I assume you are use php code to execute this query
I have two tables table1 and table2
In table1 fieldname is cert_no and in table2 fieldname is cer1,cert2,cert3,cert4,cert5
The value which was not in table2 (cer1,cert2,cert3,cert4,cert5) alone want to display
If both table has same value only transfile_file want to display
SELECT *
FROM table1
WHERE folio = '123456'
AND cm_flag !='X'
AND certificate_no NOT IN
(SELECT CONCAT(certno1,certno2,certno3,certno4,certno5,certno6,certno7,certno8,certno9,certno10)
FROM table2
WHERE tofolio = '123456'
)
If you use for example Microsoft SQL Server there is a function EXCEPT that return the different rows between 2 tables with the same fileds (same name, same types and same positions). In Oracle there is MINUS operation that is the same of EXCEPT.
In MySQL does not implement a EXCEPT or MINUS operation which is a unfortunate as it can allow for better execution plans in some cases than the alternatives.
This is a valid aternative and more performing than use NOT IN operation: realize a join is the best solution in SQL.
enter code here
SELECT a.*
FROM table1 as a
LEFT JOIN table2 as b
ON a.tofolio = b.tofolio
WHERE b.tofolio IS NULL
Try:
SELECT * FROM table1 WHERE folio = '123456' AND cm_flag !='X' AND certificate_no NOT IN (SELECT CONCAT(certno1,',',certno2,',',certno3,',',certno4,',',certno5,',',certno6,',',certno7,',',certno8,',',certno9,',',certno10) FROM table2 WHERE tofolio = '123456')
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 ...
Let's say I have to MySQL tables like this.
TBL_1
ID - NAME - DESCRIPTION
1 foo very nice
TBL_2
ID - PRICE - CATEGORY - QUANTITY
1 10 a 5
If I was to set up a PDO instance like so....
<?php
$handler = new PDO("XXXX;XXXXX","XXX","XXX");
$query = $handler->query('SELECT * FROM TBL_1');
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->id;
echo $r->name;
echo $r->description;
//echo $r->price;
//echo $r->category;
//echo $r->quantity;
}
How can I access price, category, quantity where the ID's, in both tables are equal to each other?
So for example, it would come out like this.
1 foo very nice 10 a 5
You might use JOIN:
SELECT name, description, price, category, quantity
FROM TBL_1
JOIN TBL_2
USING (id)
Hope it helps.
Assuming the ID columns contain the same values (i.e. a foreign key constrait exists because the values represent the same entity), you'll want to execute a query with an INNER JOIN on that column. By default with an INNER JOIN, if the requested value (for instance a WHERE 'ID' = 3 clause) does not exist in either table, no results will be returned. Try the following:
SELECT *
FROM `TBL_1` AS `t1`
INNER JOIN `TBL_2` AS `t2` ON `t1`.`ID` = `t2`.`ID`;
You just do an INNER JOIN on the table where on each table the id is equal.
SELECT * FROM TBL_1 INNER JOIN TBL_2 ON TBL_1.ID=TBL_2.ID;
Ive looked at other questions and answers but still dont understand which brings me here.
I have one data base two tables. lets say table1 and table2 from database.
I'm looking to grab all the information from table1 and only one column from table2 that coincides with the correct row in table1.
Example which I know is wrong:
SELECT table1.*, table2.time_stamp FROM table1, table2
WHERE table1.ticket_id=$var AND table1.user_id = table2.user_id
Basically select data from table1 then use a value from the selected table to grab the related data from table2 and join them to output them as one mysql_query. Im sure its simple and has been asked before.
edit:
I dont receive an error. SQL just returns noting. log form of this would be:
$sqlResults = mysql_query("SELECT table1.* FROM table1 WHERE table1.ticket_id=$var")
while($rowResult = mysql_fetch_array( $sqlResults )) {
$userID = $rowResult['user_id'];
$sqlResults2 = mysql_query("SELECT table2.time_stamp FROM table2
WHERE table2.user_id=$userID")
}
I want to combine that into one sql statement so i dont have to hit table2 for every row table1 has
Use a JOIN to bind the rows from table2 to those from table1:
SELECT t1.*, t2.time_stamp FROM table1 t1
JOIN table2 t2 ON t1.user_id = t2.user_id
WHERE t1.ticket_id=$var