select two tables and view in a table - php

I’ve a BD with the next tables.
TABLE detalle_contrato
TABLE detalle_tradicional
There is a relation with ID_CONTRATO and i need to view the table with the next data.
SELECT
ID_CONTRATO,
TRADICIONAL,
NOM_VARIEDAD,
SUM(CANTIDAD)
FROM detalle_contrato
WHERE ID_CONTRATO = '$ID' AND TIPO_VARIEDAD = 'TRADICIONAL';
SELECT
SUM(CANTIDAD_D)
FROM detalle_tradicional
WHERE ID_CONTRATO = '$ID'
GROUP BY NOM_VARIEDAD ";
There are a filter different in this two select and I need this in a table but i don't know together.
The idea is this:
ID_CONTRATO,
NOM_VARIEDAD,
CANTIDAD
( THIS IS THE SUM THE ALL CANTIDAD DUKE AND
LEGACY IN GROUP THE TABLE DETALLE_CONTRATO) ,
CANTIDAD_D
(TABLE DETALLE_TRADICIONAL THIS IS SUM
THE ALL DUKE AND LEGACY SEPARATE THE CANTIDAD_D
I need exactly this using the data the photos

You can use LEFT JOIN. Left join your second table with id_contrato and detalle_contrato id_contrato.
SELECT
dc.ID_CONTRATO,
dc.TRADICIONAL,
dc.NOM_VARIEDAD,
dc.IFNULL(SUM(CANTIDAD),0) AS CANTIDAD,
dc.IFNULL(SUM(CANTIDAD_D),0) AS CANTIDAD_D
FROM
detalle_contrato dc
LEFT JOIN TABLE_NAME t2 ON t2.ID_CONTRATO = dc.ID_CONTRATO
WHERE dc.ID_CONTRATO = '$ID' AND t2.TIPO_VARIEDAD = 'TRADICIONAL'

Related

referencing same row in multiple joins

I have a mySQL db named relOwner that has two columns:
OwnerID, RelationshipOwner
I am writing a query with joins that references the db:
$query = "SELECT b.Contact, b.ContactB, relOwner.OwnerID, relOwner.RelationshipOwner
FROM b
Left JOIN relOwner
ON b.Contact = relOwner.OwnerID
Left JOIN relOwner
ON b.ContactB = relOwner.OwnerID
";
How do I reference the values of RelationshipOwner individually in my php?
$RelationshipOwner = $row['RelationshipOwner'];
$RelationshipOwnerB = $row['RelationshipOwner']; <--- Get value from second JOIN
Thanks in advance.
It seems that you have two foreign key columns on table b to table relOwner (viz Contact and ContactB).
As per Sverri's comment, you will need to use a different alias for the tables (I've used ro1 and ro2) , and project different names from the different table columns (e.g. prefix the second table columns with ro2):
SELECT b.Contact, b.ContactB, ro1.OwnerID, ro1.RelationshipOwner,
ro2.OwnerID as ro2OwnerId, ro2.RelationshipOwner as ro2RelationshipOwner
FROM b -- Is this table Contact? If so then "Contact b"
Left JOIN relOwner ro1
ON b.Contact = ro1.OwnerID
Left JOIN relOwner ro2
ON b.ContactB = ro2.OwnerID;
Which you can then reference:
$row['ro2RelationshipOwner'];

PHP/MySQL Using multiple WHEREs in one SELECT query

I have 2 tables.
Table A: trades: which contains the columns: tradeID, tradeName, tradeShow, and tradeGuy.
Table B: offers: which contains the columns: tradeID, offerName, offerGuy.
I'm trying to select all columns from table A (trades) WHERE the value of "tradeShow" = 'Yes', And the value of "tradeGuy" != the user's Username. That much is easy, but I also don't want to select any records which have an offer created by the user. In other words, in table B (offers), offerGuy != Username WHERE trade ID from Table B = tradeID from Table A.
But, how do I merge these 2 conditions? I've tried this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.tradeID = t2.tradeID)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy!='$username'";
But the problem with that is it only selects the records from trades which have an offer, because of the forth line: ON (t1.tradeID = t2.tradeID), as in it only selects trades which have a record in (offers) that mentions their tradeID.
I've also tried an awkward attempt to link the 2 tables with a meaningless link by adding a "linker" column to each table with the default value of "XXX", and did this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.linkerA = t2.linkerB)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND (t2.offeringGuy!='$username' WHERE t1.tradeID=t2.tradeID)";
But the problem with that is using 2 Where clauses...
So, how do I merge the 2 conditions?
What you're looking for is called an OUTER JOIN (in this case a LEFT OUTER JOIN) which will give you null results for missing matches, something like;
SELECT *
FROM trades t1
LEFT OUTER JOIN offers t2
ON t1.tradeID = t2.tradeID AND t2.offeringGuy = '$username'
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy IS NULL
We add a condition to the LEFT JOIN that we're only interested in matches against t2.offeringGuy = '$username', which will return NULL values in t2's fields if there is no match.
Then we just check that t2.offeringGuy IS NULL to find the non matches.
I would do this with not exists rather than an explicit join:
SELECT *
FROM trades t
WHERE t.tradeShow = 'Yes' AND t.tradeGuy <> '$username' and
not exists (select 1
from offers o
where t.tradeID = o.tradeID and o.tradeGuy = '$username'
);

Getting data from 3 MySQL tables

I'm having a struggle here trying to grab some data from 3 database tables..
The idea is that users can fill out their profile with several fields, and I'm storing every profile field, field values and the users selected value in separate tables.
The structure of the tables look like this:
Table 'profile_fields'
- id
- name
- sort
- status (enum '0', '1')
Table 'profile_field_values'
- id
- profile_field_id
- name
Table 'user_profile_fields'
- user_id
- profile_field_id
- profile_field_value_id
Would be really nice if you could tell me how to construct this query, and why you used the JOIN you did.
Also, how would this table layout scale when the userbase grows?
Thank you so much in advance!
Edit:
OK, I still can't figure out how to make it return all the fields from 'profile_fields' along with the users selected option from 'user_profile_fields'. If the user hasn't selected a value, it should just be null.
This is my (non-functional) query so far:
SELECT PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type, PFV.name
FROM profile_fields PF
LEFT JOIN profile_fields_values PFV ON PFV.profile_field_id = PF.id
LEFT JOIN user_profile_fields UPF ON UPF.user_id=1 AND PF.id = UPF.profile_field_id
WHERE length(PF.name) > 0 and PF.status = '1'
ORDER BY PF.sort
This query seems to work, but it does not fetch the name of the value from 'profile_field_values':
SELECT PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type
FROM profile_fields PF
LEFT JOIN user_profile_fields UPF ON UPF.user_id =1
AND PF.id = UPF.profile_field_id
WHERE LENGTH( PF.name ) >0
AND PF.status = '1'
ORDER BY PF.sort
I think you have some unnecessary complexity in there. Maybe you should try
Table 'profile_fields'
id
name
sort
status (enum '0', '1')
Table 'profile_field_values'
id
user_id
profile_field_id
value
why are there 3 tables?
Seems like simple JOINs should work:
SELECT pf.id, pf.name, pf.sort, pf.status,
pfv.id, pfv.profile_field_id, pfv.name,
upf.user_id, upf.profile_field_id, upf.profile_field_value_id
FROM profile_fields pf
INNER JOIN profile_field_values pfv
ON pf.id = pfv.profile_field_id
INNER JOIN user_profile_fields upf
ON upf.profile_field_value_id = pfv.id AND upf.profile_field_id = pf.id
A Visual Explanation of SQL Joins
This uses an INNER JOIN to select all matching records from each table -- review the post to tell the difference between an INNER and an OUTER join.

Mysql Complex Join Query Issue

I have 5 mysql tables as described below.
clinics table
id
name
d_location_subscription table
id
clinic_id
t_id //t_id will contain a foreign key of d_cities, d_states or d_countries table
type "country" "state" "city"
d_countries table
id
name
code
d_states table
id
d_country_id
name
code
d_city table
id
d_state_id
name
code
d_location_subscription table is used to record clinic's subscription for a location(it may be a city, state or country). I'm expecting to get all subscribed cities for a specific
clinic using d_location_subscription table.
For example, if clinic A is subscribed to Texas state, I should be able to get all city ids for clinic A.
I created following sql query, it looks ugly but generate a close result what i want to achieve.
select
`d`.`id` AS `clinic_id`,
if((`dct`.`id` is not null),`dct`.`id`,if((`dct1`.`id` is not null),`dct1`.`id`,`dct2`.`id`)) AS `d_city_id`
from ((((((((
`d_location_subscriptions` `dls`
join `clinics` `d`
on((`d`.`id` = `dls`.`clinic_id`)))
left join `d_countries` `dc`
on(((`dc`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'country'))))
left join `d_states` `ds`
on((`ds`.`d_country_id` = `dc`.`id`)))
left join `d_cities` `dct2`
on((`dct2`.`d_state_id` = `ds`.`id`)))
left join `d_states` `ds1`
on(((`ds1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'state'))))
left join `d_cities` `dct`
on((`dct`.`d_state_id` = `ds1`.`id`)))
left join `d_cities` `dct1`
on(((`dct1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'city'))))
)
when there is record with type "country" in d_location_subscription table, I receive following result. total number of records returned are equal to the number of d_states table records.
How should I get rid of those Null values by changing above query?
And please advice me if this is the correct way to acheive similar functionality. Thanks in advance :)
The quickest, dirtiest way to achieve what you want is just to append this where condition to your query:
WHERE d_city_id is not null
but you might prefer to rework your query and decide where you really need LEFT joins and not INNER joins
the IF() computed column is in essence what STT LCU was trying to offer, but you can't use that directly in the where for some reason.
I've rewritten your query, but with different aliases to better follow the origination of the tables / relationships to get the data. In the end, I've added a where to test for ANY ONE of the "ID" values as NOT NULL. If they are ALL Null, the record should be excluded..
select
d.id AS clinic_id,
if(CityViaState.id is not null, CityViaState.id,
if( ByCity.id is not null, ByCity.id, CityViaCountry.id )) AS d_city_id
from
d_location_subscriptions dls
join clinics d
ON dls.clinic_id = d.id
left join d_countries ByCountry
ON dls.t_id = ByCountry.id
and dls.type = 'country'
left join d_states StateViaCountry
ON ByCountry.id = StateViaCountry.d_country_id
left join d_cities CityViaCountry
ON StateViaCountry.id = CityViaCountry.d_state_id
left join d_states ByState
ON dls.t_id = ByState.id
and dls.type = 'state'
left join d_cities CityViaState
ON ByState.id = CityViaState.d_state_id
left join d_cities ByCity
ON dls.t_id = ByCity.id
and dls.type = 'city'
where
CityViaState.id is not null
OR ByCity.id is not null
OR CityViaCountry.id is not null

SQL Advice - selecting multiple rows from a table as an innerJoin

I've been working on a project that until now has only needed to find 1 row from the joined table. But now I need to grab multiple rows..
So as it stand my sql works something like:
Select rows for each company for this particular project which alone would find company details (name, id, telephone.. blah).
Then I join a table that contains form data submitted for each company (multiple forms - so multiple records)
Until now i have been specifying one formid to look for in the join, but now i need to specify multiple ones.
If I use WHERE form_id = 1 OR form_id = 2 OR form_id = 3 ... I get a result of only the first form match that is found per company..
If I mix up the query so it looks for the forms 1st and returns multiple records for each company with different form data - that works in this sense..
But I am then looping through this array in a view and creating a table row per record (previously each row was a new company) but using the latter would cause multiple records to show for the same company.
Any way I can do this? I tried group by with the latter method but this results in only 1 record again.
SELECT DISTINCT p.project_company_has_user_id, p.project_company_has_user_project_id, p.project_company_has_user_user_id, c.company_id, c.company_hall_no, c.company_company_name, c.company_type, c.company_country, c.company_stand_number, c.company_image_file_1, p2.project_id, p2.project_name, u.user_id, u.user_username, o.orders_id, o2.order_detail_id, o2.order_detail_product_id, f2.form_question_has_answer_id, f2.form_question_has_answer_request, f2.form_question_has_answer_form_id, f2.form_question_has_answer_user_id
FROM project_company_has_user p
INNER JOIN company c ON p.project_company_has_user_company_id = c.company_id
INNER JOIN project p2 ON p.project_company_has_user_project_id = p2.project_id
INNER JOIN user u ON p.project_company_has_user_user_id = u.user_id
INNER JOIN form f ON p.project_company_has_user_project_id = f.form_project_id
LEFT JOIN orders o ON p.project_company_has_user_user_id = o.orders_user_id
LEFT JOIN order_detail o2 ON ((o2.order_detail_orders_id = o.orders_id AND (o2.order_detail_product_id = 65 OR o2.order_detail_product_id = 68 OR o2.order_detail_product_id = 64)))
LEFT JOIN form_question_has_answer f2 ON ((f2.form_question_has_answer_form_id = 297 AND f2.form_question_has_answer_user_id = p.project_company_has_user_user_id))
WHERE (f.form_template_name = "custom" AND p.project_company_has_user_garbage_collection = 0 AND p.project_company_has_user_project_id = 48) AND (LCASE(c.company_country) LIKE "%uk%" OR LCASE(c.company_country) LIKE "%uk%") ORDER BY company_company_name asc
you need another field in order_detail as o2 . this field is row_index(position),etc for positioning record
LEFT JOIN order_detail o2 ON (o2.row_index=1 AND (o2.order_detail_orders_id = o.orders_id AND (o2.order_detail_product_id = 65 OR o2.order_detail_product_id = 68 OR o2.order_detail_product_id = 64)))
Personally I would use an Outer Join for the table of which elements you need to list all matches. Should you them need to clean up that data you can build the logic into the Join Condition (as step 2). Depending on the volume of data you are handling and whether or not you need to reuse it later in the same proc, you may want to post that primary dataset into a temp table and use that as source (primary) for your later logic.
Hope that helps. If you need the code, let me know, but it is pretty straight forward.
Regards
Mac

Categories