I have two tables, Table A and Table B. For each record in table A there are many records in Table B; thus, a one to many relationship exists between tables A and B. I want to perform a query so that for each row returned from table A, all of the corresponding rows will be returned from table B. From what I understand I'll need to use a INNER Join - however, how would I go about accessing all of the returned rows through say, PHP?
$sql = "Select A.ID, B.Name * From A INNER JOIN B ON A.ID = B.ID";
A.ID | B.fName | B.lName
1 nameone lnameone
1 nametwo lnametwo
2 namethree lnamethree
4 namefour lnamefour
Now that I have the above results, I want to use PHP to loop through all of the values of B.Name only for a single A.ID at a time. So, the results I want would look like:
1.
nameOne lNameOne
nameTwo lnametwo
2. namethree lNamethree
4. nameFour lNameFour
Basically, I'm trying to group the query results by the ID in table A.
I appreciate the help very much!
Thank you,
Evan
You could just Google "php get from database," and use some normal array pre-processing, but I worry the advice you find may not be ideal. Here's what I'd do:
$pdo = new PDO('mysql:host=host;dbname=dbname', 'user', 'pass');
$result = $pdo->query(<<<SQL
SELECT
ID,
Name
FROM
A
-- Alternative to `JOIN B USING(ID)` or `JOIN B ON (A.ID = B.ID)
NATURAL JOIN B
SQL
);
$a = array();
while ($row = $result->fetch()) {
if (!isset($a[$row['ID']]) {
$a[$row['ID']] = array();
}
$a[$row['ID']][] = $row['Name'];
}
You could also GROUP BY the ID and GROUP_CONCAT the names to be exploded in PHP later to skip the manual array creation and reduce some iteration (although SQL will do more in that case).
Adding a simple ORDER BY A.ID to the SQL query would probably get you quite far in "grouping" the items together. It's difficult to give a more detailed answer without knowing exactly what you want to do with the "groups".
Related
I got the bellow piece of select statement that got level 2 child records, having problems to got deeper, can anyone help out?
SELECT
id_mobile AS ID_PROJETO,
UM.qtd_UC,
AM.qtd_AMBIENTE
FROM projetos_mobile AS PM
LEFT JOIN (
SELECT
COUNT(id) AS qtd_UC,
projeto,
data_hora_importacao,
id_uc_mobile
FROM ucs_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02'
GROUP BY projeto) AS UM
ON PM.id_mobile = UM.projeto
LEFT JOIN (
SELECT
COUNT(id_uc_mobile) AS qtd_AMBIENTE,
id_uc_mobile
FROM ucs_mobile
LEFT JOIN (
SELECT
uc
FROM ambientes_mobile AS s
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS G
ON G.uc = ucs_mobile.id_uc_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS AM
ON UM.id_uc_mobile = AM.id_uc_mobile
WHERE PM.data_hora_importacao = '2015-05-15 17:21:02'
http://sqlfiddle.com/#!9/2eecf
here is a sqlfiddle if anyone want to try a solution. I have the specific hierarchy: projeto>uc>ambiente>secao>medicoes
ucs_mobile.projeto refers to projetos_mobile.id_mobile
ambientes_mobile.uc refers to ucs_mobile.id_uc_mobile
secoes_iluminacao_mobile.ambiente refers to ambientes_mobile.id_ambiente_mobile
I need a count of each child for the parent I pass, I will have 5 functions that
return the count of each child for a given parent, for example, for a projeto parent I should have count(ucs),count(ambientes),count(secoes),count(medicoes)
So, hope you guys can help me. The database is terrible ugly but that's is what I got. Appreciate any help.
When you have really large queries like this, it can often be helpful to break them down individually, starting from the ground up and patching them together.
I started by just getting the count of each ucs_mobile row for each projetos_mobile value. You can do that by joining the two tables on the related row, and using COUNT(DISTINCT um.id) to get the number of rows. There are other ways to do it, but this particular method will scale better for the rest of your query:
SELECT pm.id, COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
GROUP BY pm.id;
The COALESCE function will be used to fill 0 counts. As long as you remember to use the DISTINCT keyword, and group by the proper id, you can just add in the child rows like so:
SELECT
pm.id,
COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc,
COALESCE(COUNT(DISTINCT am.id), 0) AS qty_am,
COALESCE(COUNT(DISTINCT sim.id), 0) AS qty_sim
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
LEFT JOIN ambientes_mobile am ON am.data_hora_importacao = um.data_hora_importacao AND am.uc = um.id_uc_mobile
LEFT JOIN secoes_iluminacao_mobile sim ON sim.data_hora_importacao = am.data_hora_importacao AND sim.ambiente = am.id_ambiente_mobile
GROUP BY pm.id;
Here is an SQL Fiddle example. NOTE I changed your sample data slightly to ensure my query was working as expected.
Also, a side note. I noticed as you went along that you kept using the same date in your WHERE clauses, so I just joined each table on the date as well, and made sure that in my very first join I looked for the date specified, which in turn will carry its way over to the other tables.
I am trying to learn about SQL joins and trying to apply them to an application I am building. I am doing a query to find a "game record" on a schedule based on a specific game id. But on this game record; for the "h_team" and the "v_team"; only the ids of the teams are on the game record. And so what I want to do is join the "teams" table and look up the two different team_names of the "h_team" and "v_team". I have it also pull in a "division name" as well using a join since only the division id is stored on the game record. I have gotten this all to work fine; except I do not know how to get the results separately for the "team_name" for h_team and v_team. Basically the key for each one is just "team_name"; I will paste in my code and then explain further:
$array_game_id6=32;
$sql = "SELECT * FROM playoff_schedule LEFT OUTER JOIN teams on playoff_schedule.h_team = teams.team_id || playoff_schedule.v_team = teams.team_id LEFT OUTER JOIN playoff_divisions on playoff_schedule.po_div_id = playoff_divisions.po_div_id WHERE tom_game_id=$array_game_id6";
foreach ($dbh->query($sql) as $resultsg39)
{
$h_team=$resultsg39[h_team];
$v_team=$resultsg39[v_team];
$po_div_id=$resultsg39[po_div_id];
$round=$resultsg39[round];
$game_id=$resultsg39[game_id];
$date=$resultsg39[date];
$timestamp=$resultsg39[timestamp];
$h_score=$resultsg39[h_score];
$v_score=$resultsg39[v_score];
$tom_game_id=$resultsg39[tom_game_id];
$h_name=$resultsg39[team_name];
$div_name=$resultsg39[playoff_name];
}
the problem comes in when i am trying to get the results of the query and store them all in the different variables…
the last two "$h_name" and "$div_name" are being pulled from the JOINs all the prior ones are on the game record itself…
what I want to do is store both the names from "v_team" and "h_team" in the respective variables $h_name and $v_name;
I have it storing the $h_name no problem; but i do not know how to make it store both $h_name and $v_name separately as they are both values in the column "team_name" from "teams" table. So I just need to somehow make it so when i get my results it can tell the difference between the two different "team_names" and I can store them in the two different variables…
If this is not clear please let me know.
Thanks!
***** UPDATE 10:49pm EST 2/5/2015
have made some progress on this but my query is not working; I think it is a problem with the aliases and such are not right; here is my non-working query as it is right now:
$sth = $dbh->prepare("SELECT home_team.team_name as home_team_name, visiting_team.team_name as visiting_team_name,
h_team, v_team, po_div_id, round, game_id, date, timestamp, h_score, v_score, tom_game_id, playoff_name FROM playoff_schedule
LEFT OUTER JOIN teams as home_team on playoff_schedule.h_team = teams.team_id
LEFT OUTER JOIN teams as visiting_team on playoff_schedule.v_team = teams.team_id
LEFT OUTER JOIN playoff_divisions on playoff_schedule.po_div_id = playoff_divisions.po_div_id
WHERE tom_game_id=$array_game_id6");
$sth->execute();
$article_list = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach ($article_list as $row => $link) {
$h_team=$link['h_team'];
$v_team=$link['v_team'];
$po_div_id=$link['po_div_id'];
$round=$link['round'];
}
if anyone can spot a problem with my new query I would really appreciate it!
I think what you are trying to do is:
select home_team.team_name as home_team_name,
visiting_team.team_name as visiting_team_name
from playoff_schedule
join team as home_team on playoff_schedule.h_team = teams.team_id
join team as visiting_team on playoff_schedule.v_team = teams.team_id
You can join to the same table as many times as you want to. In this case, it makes sense, because you really are trying to get two different bits of information.
Based on your last edit, the following query appears to work:
SELECT home_team.team_name AS home_team_name,
visiting_team.team_name AS visiting_team_name,
h_team,
v_team,
playoff_schedule.po_div_id,
round,
game_id,
date,
timestamp,
h_score,
v_score,
tom_game_id,
playoff_name
FROM playoff_schedule
LEFT OUTER JOIN teams AS home_team
ON playoff_schedule.h_team = home_team.team_id
LEFT OUTER JOIN teams AS visiting_team
ON playoff_schedule.v_team = visiting_team.team_id
LEFT OUTER JOIN playoff_divisions
ON playoff_schedule.po_div_id = playoff_divisions.po_div_id
WHERE tom_game_id=$array_game_id6
You can check the query and the schema at: SQLFiddle
A couple of thing that might be happening:
Is the query itself running?
What happens if you run the query in a mySQL client?
Are there any PHP errors in your log?
Could you post the schema itself?
Is $array_game_id6 actually an array of values? In that case, you need to use "in" as opposed to "=" in your where clause.
With regard to your updated query, I think the main thing you are missing is using the aliases in your JOIN conditions. You should keep your table aliases consistent throughout your query. Also, IMO its better to keep table aliases short so they are easier to read:
So applying those things to your query:
SELECT h.team_name as h_team_name, v.team_name as v_team_name, s.h_team, s.v_team, s.po_div_id, s.round, s.game_id, s.date, s.timestamp, s.h_score, s.v_score, s.tom_game_id, s.playoff_name
FROM playoff_schedule s
LEFT OUTER JOIN teams h ON (
s.h_team = h.team_id
)
LEFT OUTER JOIN teams as v ON (
s.v_team = v.team_id
)
LEFT OUTER JOIN playoff_divisions d ON (
s.po_div_id = d.po_div_id
)
WHERE s.tom_game_id = ?
Now I'm not 100% sure of your schema so I may have referenced some of the columns to the wrong table but you should be able to sort that out.
I have a query of a mysql database that joins two tables. In the first table it just pulls records based on an id. For the second table, there may or may not be matches based on a value in the first table. I want to get matches if there are any, otherwise, presumably those values of the resulting record set are empty.
The query seems to produce the right number of records. However, when I try to access values of some variables that should be present, I am not getting anything, either because I may be calling them the wrong name or they are not in recordset somehow. I am a bit fuzzy on mysql queries so would greatly appreciate any advice..
Table 1 parks
id | name | stateid
Table 2 parksvisited
id | visited | parkid | userid
PHP script
$sql = "SELECT *
FROM `parks` p
LEFT JOIN `parksvisited` pv
ON p.id = pv.parkid
WHERE p.stateid = '44'"
run query...
while($row = mysql_fetch_array($res))
{
if ($row['visited'] == 1) {
$visited = 1; }
else {
$visited = 0; }
Visited
}
Basically, I get stateid but I am not getting p.id or visited. It could be I am naming them wrong or possibly they are getting left out of results somehow... Thanks for any suggestions.
p.id is probably missing because each of p.id and pv.id are going to get returned as id, not as p.id or pv.id. Try this instead:
SELECT p.id pid,
p.*,
pv.id pvid,
pv.*
FROM `parks` p
LEFT JOIN `parksvisited` pv
ON p.id = pv.parkid
WHERE p.stateid = '44'
It also doesn't look like you're selecting anything from pv in your original query, just p. See if this new query takes care of visited as well. And make sure to refer to pid as $row['pid'], not $row['p.id'].
Sorry, guys.I am quite new in mysql but I do need help from getting and merging data from 2 tables.
table_a
ID | TITLE | CONTENT | DATE
table_b
ID | POST_ID | IMAGE
Here's my code
$query = "SELECT table_a.*, table_b.IMAGE FROM table_a
LEFT JOIN table_b
ON table_a.ID = table_b.POST_ID
ORDER BY table_a.DATE";
$mysql_result = mysql_query($query);
$result = array();
while ($row = mysql_fetch_assoc($mysql_result)) {
$result[] = $row;
}
print json_encode($result);
However, for those record in table_a which got more than 1 IMAGE, my json contain duplicated CONTENT with different IMAGES.
Is there any methods to merge IMAGE with the same ID into a single record?
Thanks for any helps!
You can use the GROUP_CONCAT function to group the images as a comma-delimited list in one column of your posts table.
If I understand correctly, you want to have all fields from table_a, and only one (maybe combined) field from table_b.
First of all, you have to decide what you want to get, if you have more than one image:
Only 1 image? Use MIN(table_b.IMAGE) or MAX(table_b.IMAGE) in the
following SQL
All images separated by e.g. a comma? Use GROUP_CONCAT(table_b.IMAGE SEPARATOR ',') or similar in the following SQL
Next you have to understand, that to get only one row per table_a.ID, you have to group by table_a.ID, so we have
SELECT
table_a.*,
<function from above> AS image
FROM table_a
LEFT JOIN table_b
ON table_a.ID = table_b.POST_ID
GROUP BY table_a.ID
ORDER BY table_a.DATE
I believe what you need is something like this:
SELECT table_a.*, GROUP_CONCAT(table_b.IMAGE) FROM table_a
LEFT JOIN table_b ON table_a.ID = table_b.POST_ID
GROUP BY table_a.*
ORDER BY table_a.DATE
(Not sure if you have to spell out the GROUP BY clause, listing field names individually, or whether .* notation will be accepted here.)
You can perhaps use JOIN instead of LEFT JOIN . In this way it will only load one row
or the other way
put GROUP BY a.ID jsut before ORDER BY...
SELECT * FROM dog WHERE (SELECT calluser FROM jos_users WHERE `user_id`='".$cid."')=Subcode
$cid is the identifier in jos_users, which tells us which users we're fetching data about
The data I want to fetch is within "dog", and calluser is the identifier between the two (which tells us who's dogs are who's)
I need to be able to call only the dogs relevant to the user in question, but it also has to be performed in one query. Can anyone help? Much appreciated.
You need to use joins.
Read this tutorial: http://www.tizag.com/mysqlTutorial/
Your query should look something like this:
$cid = mysql_real_escape_string($_GET['cid']);
$query = "SELECT d.* FROM dog d
INNER JOIN jos_users ju ON (d.user_id = ju.id)
WHERE ju.id = '$cid' ";
If I got you right (and the id column in the dog-table links to the calluser column in the jos_user-table) the query should be
SELECT d.* FROM dog AS d JOIN jos_user AS u ON d.id = u.calluser WHERE u.user_id = '$cid'
If not please explain your data structure in more detail (maybee small ER diagram).