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'];
Related
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'
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
I have two tables and joined them to one different table
1 table named 'rec_dept'
id_dept
id_divisi
nama_dept
2 table named 'rec_divisi'
id_divisi
nama_div
3 joined table named 'rec_divdep'
id_divdep
id_divisi
id_dept
How to get nama_dept where in the same id_divisi?
Maybe you're looking for this:
SELECT `nama_dept` FROM `rec_dept` WHERE `id_divisi` IN (SELECT `id_divisi` FROM `rec_divdep`);
Hope that helps
you can do a SELECT query with a LEFT JOIN function to get data
SELECT a.`nama_dept` FROM `rec_dept` a
LEFT JOIN `rec_divisi` b
ON a.`id_divisi` = b.`id_divisi`
ORDER BY a.`id_divisi` ASC
SELECT documentation
LEFT JOIN documentation
select a.id_dept, a.id_divisi, a.nama_dept, b.id_divisi, b.nama_div, c.id_divdep, c.id_divisi from rec_divdep as c left join rec_divisi as b on (c.id_divisi = b.id_divisi) left join rec_dept as a on (c.id_divisi = a.id_divisi)
what database do you use. I code mine as mysql, basically I condition the three tables that has same id_divisi. I did not test it but I am pretty sure of the logic based on what I understand.
I need to pull data from two tables, and it's a bit over my head :
The first tables contains a list of members (member_id, username, email ...)
The second table stores relations between members (id, member_id, friend_id)
When a member adds another member as a friend, both member_ids are stored in the second table.
Now I need to output that second table, I'd like to output usernames instead of numbers :
example :
{username corresponding to member_id} added {username corresponding to friend_id} as a friend
Can someone help with the query ?
You need to perform a double join on members
SELECT mem1.username, mem2.username
FROM members mem1
INNER JOIN relations
ON mem1.member_id = relations.member_id
INNER JOIN member mem2
ON relations.friend_id = mem2.member_id
Something like:
select tb1.username as member_name,
tb2.username as friend_name
from membertable as tb1
inner join
(
membertable as tb2,
memberrelationstable
)
on
(
tb1.member_id = memberrelationstable.member_id and
tb2.member_id = memberrelationstable.friend_id
)
This is how I would do it:
SELECT member.username AS member_username, friend.username AS friend_username
FROM relations
INNER JOIN members AS member
ON relations.member_id = member.member_id
INNER JOIN members AS friend
ON relations.friend_id = mem2.member_id
I've spaced it so that you can easily see how we're joining the members table twice, and simple giving it a different name both times.
Whenever something is followed by AS, it means that you're giving it another name. This allows you to use the same table multiple times in a single query.
So a user selects from a drop down list a value. I take this value, put it into a variable, then select from the database the ID value of that table A holding the selected value also.
So now I'm trying to use that ID value to get to a many-to-many relationship table that has the selected value from table A to a different table B. The many-to-many relationship table has both IDs. How can I compare this using PHP?
So it would be like:
$A = $_POST['a'];
$sql = "SELECT a, aID from TABLEA WHERE a = $A";
What do I do then to compare the aID with the many-to-many relationships table, then get the other ID in that table and then take that ID to get values from table B?
You can do this with a join in your SQL:
SELECT table_b.* FROM ab_association
LEFT JOIN table_b ON table_b.id = ab_association.b_id
WHERE ab_association.a_id = $specified_id;
That assumes that your many-to-many join table is called ab_association and has two columns, one called a_id that corresponds to table_a.id, and b_id that corresponds to table_b.id.
Update: I removed the table name aliases since they seem to be confusing you.
Another Update: In PHP, here's how you would do that (sans business logic):
<?
// connect to db here
$a_id = mysql_real_escape_string($_POST['a_id']);
$result = mysql_query("SELECT table_b.* FROM ab_association LEFT JOIN table_b ON table_b.id = ab_association.b_id WHERE ab_association.a_id = $a_id;");
// in your view/template
while(false !== (mysql_fetch_object($result))) {
// build your output for each row
}
?>
SELECT *
FROM table_a
LEFT JOIN ab_association ON table_a.aID = ab_association.aID
LEFT JOIN table_b ON table_b.bID = ab_association.bID
WHERE table_a.a = $A
Notes:
I used some underscores in tablenames, so table_a instead of TABLEA (just like Coreyward did) to distinguish between sql and names
You should specify the columns you need instead of 'SELECT *' if many columns aren't needed
You can use JOIN instead of LEFT JOIN if you want get an empty recordset when no match in the many-to-many is found. (Using a LEFT JOIN has the advantage you still have access to the columns in table_A)
it is never wise to use $_POST-vars directly in your queries, this is a serious security risk (SQL injection.)