Inner join MYSQL query not working - php

I have a table structure with three tables: profiles, profile_subrubriek and rubrieken. I query the data with the following query:
SELECT profiles.hoofdrubriek, profiles.plaats
, profiles.bedrijfsnaam, profiles.gemeente, profiles.bedrijfsslogan
, profiles.straatnaam, profiles.huisnummer, profiles.postcode
, profiles.telefoonnummer, profiles.fax, profiles.email
, profiles.website, profiles.bedrijfslogo
FROM profiles INNER JOIN profile_subrubriek ON profiles.ID=profile_subrubriek.profile_id
INNER JOIN rubrieken ON profile_subrubriek.subrubriek_id=rubrieken.ID
where (
rubrieken.rubriek = 'Aannemersbedrijven'
OR
profiles.hoofdrubriek = 'Aannemersbedrijven')
AND profiles.gemeente = 'Dongen'
The result, 0 rows. That is not correct. If I take out the Inner Join and only incorporate the 'hoofdrubriek' column in the WHERE clausule I get about 25 rows as a result, that is correct. So this query (modified version of the above) does actually work:
SELECT profiles.hoofdrubriek, profiles.plaats, profiles.bedrijfsnaam
, profiles.gemeente, profiles.bedrijfsslogan, profiles.straatnaam
, profiles.huisnummer, profiles.postcode, profiles.telefoonnummer
, profiles.fax, profiles.email, profiles.website, profiles.bedrijfslogo
FROM profiles where (profiles.hoofdrubriek = 'Aannemersbedrijven')
AND profiles.gemeente = 'Dongen'
What am I doing wrong?
Thanks!

Probably the joined tables don't contain referenced values. Try LEFT JOIN instead of INNER JOIN.

Start troubleshooting with this query.
select count(*) records
FROM profiles INNER JOIN profile_subrubriek ON profiles.ID=profile_subrubriek.profile_id
If records is greater than 1, add this line and run it again:
INNER JOIN rubrieken ON profile_subrubriek.subrubriek_id=rubrieken.ID
Keep adding bits of your original query, one by one, until records is zero. The last thing you added will be the reason.

Related

MySQL: Multiple tables (one time all columns, three times only a single column)

$sql = 'SELECT *
FROM table_all ta
INNER JOIN table11 ta11
ON ta11.column1 = ta.column1
INNER JOIN table12 ta12
ON ta12.column2 = ta.column2
INNER JOIN table13 ta13
ON ta13.column3 = ta.column3';
This is a sql statement of a PHP-programm that I am currently working on. It works fine actually, but I am unsatisfied with the outcome of this statement. It would be nice to have
only the content of the table_all and then
only the three columns of those other three tables (table11, table12, table13).
The asterisk creates some problems in this regard.
The length of table_all is not known. It is able to change in size.
I tried Union and multiple selects, but only received errors. How would one deal with such a problem?
You can try specifying which columns do you want to get.
As you can see asterisk returns all columns.
You should use something like:
$sql = 'SELECT ta11.column1, taa12.column2, ta13.column13
FROM table_all ta
INNER JOIN table11 ta11
ON ta11.column1 = ta.column1
INNER JOIN table12 ta12
ON ta12.column2 = ta.column2
INNER JOIN table13 ta13
ON ta13.column3 = ta.column3';
I don't see a point in getting ta11.column1, taa12.column2, ta13.column13 because these fields are already in table_all (you use these columns in Join). But you can select any columns you want that way.

Assistance with MySQL left outer join and differentiating query results from same key

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.

Join a query into another query with column computation

I have three tables named issue_details, nature_payments, and rci_records. Now I have this query which joins this three tables.
SELECT issue_details.issue_date AS Date,
issue_details.check_no AS Check_No,
payees.payee_name AS Name_payee,
nature_payments.nature_payment AS Nature_of_Payment,
issue_details.issue_amount AS Checks_issued,
issue_details.nca_balance AS Nca_balance
FROM
issue_details
INNER JOIN
nature_payments ON
issue_details.nature_id = nature_payments.nature_id
INNER JOIN
payees ON
issue_details.payee_id = payees.payee_id
ORDER BY Date Asc, Check_no ASC
On my column in Nca_balance, this is a computed differences of every issuances of check. But you may not know what really the process of how I got the difference but to make it simple, let's say that I have another query
that dynamically get also the difference of this nca_balance column. Here is the query:
SELECT r.*,
(#tot := #tot - issue_amount) as bank_balance
FROM (SELECT #tot := SUM(nca_amount) as nca_total FROM nca
WHERE account_type = 'DBP-TRUST' AND
year(issue_date) = year('2015-01-11') AND
month(issue_date) = month('2015-01-11')
)
vars CROSS JOIN issue_details r
WHERE r.account_type = 'DBP-TRUST' AND
r.issue_date = '2015-01-11'
ORDER BY r.issue_date, r.check_no
I know it you may not get my point but I just want to replace the first query of the line
issue_details.nca_balance AS Nca_balance
with my own computation on my second query.
Please help me combine those two query into a single query. Thanks

Better way to do this subquery

Let's say I have this query:
<?
$qi = $db->prepare('SELECT one.id, one.Value, two.Name, three.nfid, temp.Name AS Alias
FROM one
INNER JOIN two ON one.fid = two.id
LEFT OUTER JOIN three ON two.fid = three.fid
LEFT OUTER JOIN (SELECT id,Name FROM two) AS temp ON three.nfid = temp.id
WHERE one.rid = ?
ORDER BY one.id ASC');
$qi->execute( array( $id ) );
?>
Connections between the tables are:
Table one contains a number of rows with the fields one.Value, one.rid and one.fid.
fid is a connection to table two which contains the two.Name of the items (one.fid = two.id).
But sometimes the item is an alias for another item, which is why table three exists. It contains the fields three.fid and three.newfid where three.newfid = two.id (but for another item with another two.Name)
The query is supposed to fetch all rows from one with a certain one.rid and get one.Value, two.Name and if there is an three.fid for this one.fid, get two.Name for three.newfid and call it Alias.
Is there a way to improve this query or solve the problem in another way? Perhaps reshape the layout of the database? It is currently quite slow. The example here have been simplified to make it more general.
Thank you.
The subquery in parentheses forces MYSQL to ignore its indexes, which makes it take a long time. Better to directly join two as temp. As long as you always put two.[field] and temp.[field], it will tell them apart just fine.
SELECT one.id, one.Value, two.Name, three.nfid, temp.Name AS Alias
FROM one
INNER JOIN two ON one.fid = two.id
LEFT OUTER JOIN three ON two.fid = three.fid
LEFT OUTER JOIN two AS temp ON three.nfid = temp.id
WHERE one.rid = ?
ORDER BY one.id ASC

Mysql Join Won't Select

I have been doing a lots of research online and from my understanding i think my query is ok
That is why i need your help to point me out what im doing wrong.
What My Query Should Do
My query should fetch our stock level from both warehouse
Problem Is
if the product is not in both warehouse the query dont give any result.
Ok so first i have two database of warehouse stock level. that look like that.
Databases
-warehouse1
-warehouse2
Table
-product
Columns
-id
-SKU
-qty
So my Query is
SELECT
warehouse1.product.id as 1_id,
warehouse2.product.id as 2_id ,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty,
warehouse2.product.qty as 2_qty
FROM `warehouse1`.`product`
LEFT JOIN `warehouse2`.`product`
ON
(`warehouse1`.`product`.`SKU` = `warehouse2`.`product`.`SKU`)
WHERE
warehouse1.product.SKU = '$sku'
OR
warehouse2.product.SKU = '$sku'
ORDER BY
(1_qty + 2_qty) DESC
if i make the where clause like this
WHERE warehouse1.product.SKU = '$sku'
it is then working but i can't get stock from both warehouse.
What should i do if i want to receive the stock level from both warehouse even if there is no product that im asking for in this database.
Thanks
Try a FULL OUTER JOIN. You're using a LEFT JOIN. That requires that the DB fetch all records that match your WHERE clause on the LEFT side of the join, which is warehouse1, and any potentially matching records from warehouse2 (the right side of the join). If a SKU exists only in warehouse2, you don't see it.
Switching to a FULL OUTER JOIN forces the DB to fetch all matching records from BOTH sides of the join, regardless of which side(s) the matching records exist on.
you can also do this with a union
(SELECT
warehouse1.product.id as 1_id,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty
FROM `warehouse1`.`product`
WHERE
warehouse1.product.SKU = '$sku' )
union
(SELECT
warehouse2.product.id as 2_id ,
warehouse2.product.SKU,
warehouse2.product.qty as 2_qty
FROM `warehouse2`.`product`
WHERE warehouse2.product.SKU = '$sku' )
Combine your OR's in () (... OR ...):
SELECT
warehouse1.product.id as 1_id,
warehouse2.product.id as 2_id ,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty,
warehouse2.product.qty as 2_qty
FROM `warehouse1`.`product`
LEFT JOIN `warehouse2`.`product`
ON
(`warehouse1`.`product`.`SKU` = `warehouse2`.`product`.`SKU`)
WHERE (warehouse1.product.SKU = '$sku'
OR
warehouse2.product.SKU = '$sku')
ORDER BY
(1_qty + 2_qty) DESC

Categories