PHP match tables from 2 different MySQL Databases - php

I have this PHP Code:
$sql="SELECT * from client where level = '100' group by parent_client_id ";
$rs=mysql_query($sql,$pbx01_conn);
while($result=mysql_fetch_array($rs))
{
$sql2="SELECT * from customer where customerid = '".$result["parent_client_id"]."' ";
echo $sql2.'<br>';
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
if(mysql_num_rows($rs2) > 0)
{
$result2=mysql_fetch_array($rs2);
echo $result2["company"].'<br>';
}
}
I am trying to match the parent_client_id column in the client table with the customerid column in the customer table.
the customer and client tables are in 2 different databases.
I want to display the company column from the client table if there is no match between the two
can i do this using php?

SELECT company FROM db1.client LEFT JOIN db2.customer ON db1.client.parent_client_id=db2.customer.customerid
WHERE customerid IS null

Use databasename.tablename syntax if your tables are in different databases.

Try this:
SELECT c.company FROM client c INNER JOIN customer cu ON cu.customerid = c.parent_client_id WHERE c.level = '100' GROUP BY c.parent_client_id

Related

select two tables and view in a table

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'

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'
);

how to fetch content from one table according to results from another table in mysql

I have two mysql tables with content one is called petitions
{"success":1,"petitions":[{"id":"6","name":"should he go","timestamp":"2013-10-26 03:02:44"},{"id":"3","name":"Olara Otunu should get married","timestamp":"2013-10-24 14:33:53"},{"id":"4","name":"Teachers deserve 30 not 20 salary rise","timestamp":"2013-10-24 14:33:53"},{"id":"5","name":"Prostitution should be banned","timestamp":"2013-10-24 14:33:53"},{"id":"1","name":"Has Jennifer Musisi done great work for Kampala","timestamp":"2013-10-24 14:32:58"},{"id":"2","name":"Do lecturers deserve 100% salary increase","timestamp":"2013-10-24 14:32:58"}]}
and the other table is called petition_response
{"success":1,"petition_response":[{"id":"2","petitionID":"2","yes":"0","no":"1","memberID":"14","timestamp":"2013-11-02 08:36:20"},{"id":"1","petitionID":"1","yes":"1","no":"0","memberID":"14","timestamp":"2013-11-01 21:26:02"}]}
I need to select * petitions which have no response in the petition_response. But if they have any response in the petition_response table then the memberID should not be equal to 14
I have tried this code below but its not working
$result = mysql_query("select * from petition_response where memberID='14' order by timestamp DESC", $db->connect());
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$result2 = mysql_query("select * from petitions where id != '$id' order by timestamp DESC", $db->connect());
}
return $result2;
You're looking to effect an anti-join, for which there are three possibilities in MySQL:
Using NOT IN:
SELECT *
FROM petitions
WHERE id NOT IN (
SELECT petitionID
FROM petition_response
WHERE memberID = 14
)
Using NOT EXISTS:
SELECT *
FROM petitions p
WHERE NOT EXISTS (
SELECT *
FROM petition_response r
WHERE r.petitionID = p.id
AND r.memberID = 14
LIMIT 1
)
Using an OUTER JOIN:
SELECT p.*
FROM petitions p
LEFT OUTER JOIN petition_response r
ON r.petitionID = p.id AND r.memberID = 14
WHERE r.petitionID IS NULL
See them on sqlfiddle.
According to #Quassnoi's analysis:
Summary
MySQL can optimize all three methods to do a sort of NESTED LOOPS ANTI JOIN.
It will take each value from t_left and look it up in the index on t_right.value. In case of an index hit or an index miss, the corresponding predicate will immediately return FALSE or TRUE, respectively, and the decision to return the row from t_left or not will be made immediately without examining other rows in t_right.
However, these three methods generate three different plans which are executed by three different pieces of code. The code that executes EXISTS predicate is about 30% less efficient than those that execute index_subquery and LEFT JOIN optimized to use Not exists method.
That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.
$query = "
SELECT *
FROM petition_response pr
LEFT
JOIN petitions p
ON p.id = pr.id
WHERE pr.memberID = 14
AND p.id IS NULL
ORDER
BY pr.timestamp DESC;
";

Statement to Count(*) related rows on other table

I have two tables named patient_list and dentist_list where in the dentist can have many patients, I want to get how many patients the dentist has and ordered it.
I have here a sample code where I get each patient of doctor:
$query_dentist = "SELECT * FROM dentist_list ORDER BY ID ASC";
$res_dentist = mysql_query($query_dentist);
if ($res_dentist) {
while ($row_dentist = mysql_fetch_array($res_dentist)) {
}
}
After I get all the dentists, I create a new query inside the while where I will get all the patient count.
$dentist_id = $row_dentist['id'];
$query_patient= "SELECT COUNT(*) as patient_num FROM patient_list
WHERE dentist_id ='$dentist_id'";
$res_patient=mysql_query($query_patient);
if($res_patient)
{
while($row_patient=mysql_fetch_array($res_patient))
{
}
}
For example the output of query is:
doctor 1 has 10 patient
doctor 2 has 5 patient
doctor 3 has 100 patient
Rather than using PHP, is it possible to use a MySQL statement instead? I will create one query only because i need it to sort by number of patient.
You can try using this code:
select d.Name, -- <- put dentist information here
(select count(1) from patient_list p where p.dentist_id = d.dentist_id)
from dentist_list d
order by 2 asc -- <- order by by the 2nd field that is (select count(1...
SELECT COUNT(*) AS Patient_Num FROM patient_list GROUP BY dentist_id ORDER BY 1

Relational Database query MySQL

I have modified the names of my Tables. The sportevents table is the main table and it should get its data from the tables: event_date, events, results, and members. Is there a way to do this. Please not i need to keep this structure.
sportevents (link table)
• id
• event_id
• date_id
• result_id
event_date
• id
• date
events
• id
• eventname
results
• id
• result
members
• id (the ID number of a person)
userlogin
• id
• username
• password
I have managed to get it right without joins. The following:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo $row['eventname'];
echo " - ";
echo $row['year'];
echo " - ";
echo $row['result'];
}
Gives me this:
Karoo Cycle - 2008 - 1h14mins
I presume that you have member's data stored in to $_SESSION['member'] or smth. And i dont know exactly why you have separated tabes on event, event_date (there should be one in my perspective) and I guess that main_events is something like event's group/category.
and you are missing MEMBER - EVENT link. add field 'member_id' to the events table.
If that's what it is then it's something like that.
$q = 'SELECT e.*, ed.year, r.result FROM events As e
LEFT JOIN event_date As ed ON ed.id = e.id
LEFT JOIN result As r ON r.id = e.id
WHERE e.member_id = ' . $_SESSION['member']['id'];
from that you get
event id, event name, event year, result. "JohnSmith" you can get from $_SESSION['member'].
If you decide not to use separate tables for event, event_date, result and use only one table with more fields u can do this without any LEFT JOINS just very simple SELECT query.
First, you need to link event with a result. It depends on your domain model, but I'll assume you have only one result per event, so I'll add result_id to the events table. Also, you need to link members with events somehow, I'll use
events_members
member_id
main_event_id
table. With this vcersion you'll be able to have multiple members participate in multiple events.
And finally, the query would be something like the following:
select m.username, e.eventname, y.year, r.result
from members m
join events_members em on em.member_id = m.id
join main_events me on em.main_event_id = me.id
join event e on e.id = me.event_id
join year y on y.id = me.year_id
join result r on r.id = e.result_id
where m.username = $username

Categories