How to check id of one table to another table? - php

How to find whether distinct value id of one table exits to another tables or not using php.
For example: Let table1 have id (not primary or unique) 4, 5, 6, 4, 6, how to check if id of table2 have 4, 5, 6 or not ?
$query_check= "select distinct(project_code) from table1";
$projects_check = mysql_query($query_check);
while ($result_check = mysql_fetch_array($projects_check)){
$all[] = $result_check[0];
}
$query = "select id from table2";
$projects = mysql_query($query);
while ($result = mysql_fetch_array($projects)){
foreach($all as $all_val){
$pro_code = $result[0];
if($pro_code != $all_val){ }
}
}

This SQL may help:
SELECT table2.id
FROM table2
WHERE table2.id NOT IN (
SELECT DISTINCT table1.id
FROM table1
)

SELECT table2.id
FROM table2
WHERE table2.id IN (
SELECT DISTINCT table1.id
FROM table1
)

To get a list of all the project codes from table1 that are ids in table2:-
SELECT DISTINCT table1.project_code
FROM table1
INNER JOIN table2
ON table1.project_code = table2.id
To get a list of all the project codes from table1 that are NOT ids in table2
SELECT DISTINCT table1.project_code
FROM table1
LEFT OUTER JOIN table2
ON table1.project_code = table2.id
WHERE table2.id IS NULL
If it is the entries on 2 that you want that are not on 1
SELECT DISTINCT table2.id
FROM table2
LEFT OUTER JOIN table1
ON table1.project_code = table2.id
WHERE table1.project_code IS NULL

Related

SELECT * FROM table1, table2, table3 [duplicate]

This question already has answers here:
SQL Inner-join with 3 tables?
(12 answers)
Closed 5 years ago.
I have a problem ...
In table1 I have an id, I have to compare that id in table2, then fetch the second id that is in table2 and compare it to table3 and get as a result a datum.
Example
TABLE1
ID NAME ECC...
1 Jhon
2 Frank
TABLE2
ID ID2 ECC..
1 4
2 8
TABLE3
ID NAME
4 Sea
8 Hello
If I look for id 1, the result must be Sea
If I look for id 2 the result must be Hello
Thanks!
SELECT Table3.NAME
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.ID
INNER JOIN Table3
ON Table3.ID = Table2.ID2
WHERE Table1.ID = 1 -- Your Search here
You should use joins.
Your query will look like :
SELECT t3.name
FROM table3 t3
LEFT JOIN table2 t2 ON t3.id = t2.id2
LEFT JOIN table1 t1 ON t2.id2 = t1.id
WHERE t1.id = <your_number>
select Table2.Id,Table3.Name from Table1 inner join Table2 on Table2.ID2 = Table3.Id
Query:
SELECT a.name As Name FROM table3 a JOIN
(SELECT b.id2 AS id FROM table1 a JOIN table2 b ON a.id = b.id)b
ON a.id = b.id where b.id = <your id number (1,2) Anything>
Should be something like this:
select table3.name as name3
from table3
where table3.ID = table2.ID2
and table2.ID = table1.ID
and table1.ID = <YOURNUMBERHERE>

Insert Join with limit - Mysql

How do I go about doing an update with a join while using a limit
Error - Illegal use of limit operator
UPDATE
table1
INNER JOIN table2 ON table1.id = table2.id
SET
table1.field = 'your_value'
WHERE
table1.id = table2.id
LIMIT 1500
Possible solution, it's a bit of a hack
SET #tmp_c = 0;
UPDATE
table1
INNER JOIN table2 ON table1.id = table2.id
INNER JOIN table3 ON table2.id = table3.id
SET
table1.remove_date = NOW() - INTERVAL 5 MONTH
WHERE
table1.active = 1
AND
(IF (table1.active = 1, #tmp_c := #tmp_c + 1 , 0 )) //This is to only increment the counter if the whole where matches
AND
#tmp_c <= 15 //Start ignoring row items as soon as it exceeds the limit amount
;
if you want limit you should use a subselect and join this
UPDATE table1
INNER JOIN ( select * from table1
INNER JOIN table2 ON table1.id = table2.id
LIMIT 1500 ) t on t.id = table1.id
SET table1.field = 'your_value'

PHP SQL output issue adding a third table to a query

I am currently using this script below.
$query = mysql_query("SELECT * FROM `venues` as table1
LEFT JOIN `follows` as table2 on table1.venue_id = table2.venue_id
WHERE table2.user_id = $userid");
The tables have these fields:
Table1:
id, venue_id, user_id...
Table2:
id, venue_id, user_id...
The query above returns 5 records.
Now....
I need to add a third table to the above script Table3
Table 3 fields also contains id, venue_id, user_id... BUT I don't what it in the WHERE of the script.
I've tried adding a LEFT JOIN to the script above to add the third table like this:
$query = mysql_query("SELECT * FROM `venues` as table1
LEFT JOIN `follows` as table2 on table1.venue_id = table2.venue_id
LEFT JOIN `stats` as table3 on table1.venue_id = table3.venue_id
WHERE table2.user_id = $userid");
The Stats table only contains 1 record.
Now, my problem is that the query above it's echoing the data on ALL the records and not just the one.
My question is...What I'm I doing wrong on the line I added:
LEFT JOIN stats as table3 on table1.venue_id = table3.venue_id ?
OK, I think you want to also join on the user_id. So
SELECT
*
FROM
`venues` AS table1
LEFT JOIN `follows` AS table2 USING (venue_id)
LEFT JOIN `stats` AS table3 USING (venue_id, user_id)
WHERE
table2.user_id = $userid
is my solution
If you only want to include record from table1 that have non null records in table3 then you need to use INNER JOIN and not a LEFT JOIN. See the MySQL documentation for JOIN
$query = mysql_query("SELECT * FROM `venues` as table1
LEFT JOIN `follows` as table2 on table1.venue_id = table2.venue_id
INNER JOIN `stats` as table3 on table1.venue_id = table3.venue_id
WHERE table2.user_id = $userid");
The "INNER" is not needed explicitly. Joins are INNER joins by default
You're not limiting the records at all. Use this instead:
$query = mysql_query("SELECT * FROM `venues` as table1
LEFT JOIN `follows` as table2 on table1.venue_id = table2.venue_id
LEFT JOIN `stats` as table3 on table1.venue_id = table3.venue_id
WHERE table2.user_id = $userid AND table3.venue_id IS NOT NULL");
You can use an INNER JOIN rather than an LEFT JOIN. See this SO post to make it clear or this blog article

php multiple mysql commands in array

Is it possible build an array of SQL commands to query the DB? What I have is three tables, each have columns with amounts due. Would like to select anything that is due and display on screen so it can be invoiced (preferably in a table) and each row with it's respective customers dues.
I can select everything that is due using UNION ALL between the three tables, however I cant figure out how to list them by ID in the table row.
Below is what I have so far. At this pace I'll have to run each query separately and list them in three separate lists. Suggestions?
<table>
<tr>
<th> ID</th>
<th> Cost 1</th>
<th> Cost 2</th>
<th> Cost 3</th>
</tr>
<?php
$list1 = "SELECT ID, Cost FROM Table1 WHERE Invoiced IS NULL;";
//$list2 = "SELECT ID, Price2 FROM Table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate';";
//$list3 = "SELECT ID, Price3 FROM Table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'";
$result = mysql_query($list1, $link) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$num_fields = mysql_num_fields($result);
for ($i=0; $i<$num_rows; $i++) {
for ($j=0; $j<$num_fields; $j++) {
$invoice[$i][mysql_fieldname($result,$j)] = mysql_result($result,$i,mysql_field_name($result,$j));
}
}
//eventually the order it should be listed on screen
for($i=0; $i<count($invoice); $i++) {
echo "<tr><td>".$invoice[$i]["ID"]."</td>
<td>".$invoice[$i]["Cost"]."</td>
<td>".$invoice[$i]["Price2"]."</td>
<td>".$invoice[$i]["Price3"]."</td></tr>";
}
?>
</table>
Edit after comment:
Query being passed and returning syntax error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'all LEFT JOIN table1 ON all.ID = table1.ID LEFT JOIN t' at line 7:
$query = "
SELECT all.ID, table1.Cost1, table2.Price2, tabl3.Price3
FROM
(SELECT ID, Cost1 FROM table1 WHERE Invoiced IS NULL
UNION
SELECT ID, Price2 FROM table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'
UNION
SELECT ID, Price3 FROM table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') AS all
LEFT JOIN table1 ON all.ID = table1.ID
LEFT JOIN table2 ON all.ID = table2.ID
LEFT JOIN table3 ON all.ID = table3.ID
";
From the table header you have created above which places the three Cost columns in a single row by ID, you seem to imply that you want to to JOIN the three tables together on their ID. I am using a LEFT JOIN here, to be sure that all rows from Table1 are present, even if there is no corresponding row in either of the other two tables.
SELECT
Table1.ID,
Table1.Cost as Cost1,
Table2.Price2 AS Cost2,
Table3.Price3 AS Cost3
FROM
Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
LEFT JOIN Table3 ON Table1.ID = Table3.ID
WHERE
Table1.Invoiced IS NULL
AND Table2.Expiration BETWEEN '$curDate' AND '$maxDate'
AND Table3.Expiration BETWEEN '$curDate' AND '$maxDate'
Update after comments:
In the case that Table2 may have an ID not held in Table1 or Table3, for example (where Table1.ID can't be considered authoritative), you can get the total set of DISTINCT ID from all 3 tables via a UNION and use that to join against:
SELECT
allID.ID,
Table1.Cost1,
Table2.Price2 AS Cost2,
Table2.Price3 AS Cost3
FROM
/* Subquery gets a distinct set of IDs from all tables via UNION
so the outer query has a complete list to join against the other tables */
(
SELECT ID FROM Table1
UNION SELECT ID FROM Table2
UNION SELECT ID FROM Table3
) allID
LEFT JOIN Table1 ON allID.ID = Table1.ID
LEFT JOIN Table2 ON allID.ID = Table2.ID
LEFT JOIN Table3 ON allID.ID = Table3.ID
/* Sorry, forgot the WHERE clause here */
WHERE
Table1.Invoiced IS NULL
AND Table2.Expiration BETWEEN '$curDate' AND '$maxDate'
AND Table3.Expiration BETWEEN '$curDate' AND '$maxDate'
Note that the existence of three tables with nearly identical column structures in a one-to-one relationship probably implies a design problem. You might consider combining these into a single table.
A further note about the PHP:
In PHP, we almost never use an incremental for loop for iteration as you would in C/C++. Instead, we typically make use of a foreach or when fetching rows from a query, a while loop.
// Fetch in a while loop
$invoice = array();
// $result is your query resource as you already have it...
while ($row = mysql_fetch_assoc($result)) {
// Accumulate rows into $invoice array
$invoice[] = $row;
}
// Then loop over the array:
foreach ($invoice as $inv) {
echo "<tr>
<td>{$inv['ID']}</td>
<td>{$inv['Cost1']}</td>
<td>{$inv['Cost2']}</td>
<td>{$inv['Cost3']}</td>
</tr>";
}
Final update:
Yes, the WHERE clause will restrict for all conditions met. If you need to limit them individually, you must do so in subqueries which are then joined together, using the same UNION subquery to get the distinct set of ID
SELECT
allID.ID,
T1.Cost1,
T2.Price2 AS Cost2,
T3.Price3 AS Cost3
FROM
(
SELECT ID FROM Table1
UNION SELECT ID FROM Table2
UNION SELECT ID FROM Table3
) allID
LEFT JOIN (SELECT ID, Cost AS Cost1 FROM Table1 WHERE Invoiced IS NULL) T1 ON allID.ID = T1.ID
LEFT JOIN (SELECT ID, Price2 AS Cost2 FROM Table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') T2 ON allID.ID = T2.ID
LEFT JOIN (SELECT ID, Price3 AS Cost3 FROM Table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') T3 ON allID.ID = T3.ID

Fetch data from multiple MySQL tables

My two tables look like this:
TABLE1 TABLE2
+--------------------+ +--------------------+
|field1|field2|field3| and |field2|field4|field5|
+--------------------+ +--------------------+
I am already running a SELECT query for TABLE1, and assorting all of the data into variables:
$query = "SELECT * FROM TABLE1 WHERE field2 = 2";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if((!is_bool($result) || $result) && $num_rows) {
while($row = mysql_fetch_array($result))
{
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
}
}
What I want to do is get the data from 'field4' on TABLE2 and add it to my variables. I would want to get field4 WHERE field2 = 2
SELECT
t1.*,
t2.field4
FROM
TABLE1 AS t1,
TABLE2 AS t2
WHERE
t1.field2 = 2
AND
t1.field2 = t2.field2
You want to join the two table which can be done explicitly (using the JOIN operator or one of its variants) our implicitly (by SELECTing from multiple tables directly).
From your description, I suppose that you want to do the join where field2 in the two tables have the same value (2).
If TABLE2 will not always provide a valid join candidate but you still want the data from TABLE1, you should use a LEFT JOIN (giving NULL for field4 where nothing matched):
SELECT
t1.*,
t2.field4
FROM
TABLE1 AS t1
LEFT JOIN
TABLE2 AS t2
ON
t1.field2 = t2.field2
WHERE
t1.field2 = 2
http://en.wikipedia.org/wiki/Join_%28SQL%29
You need to use a JOIN:
SELECT TABLE1.*,TABLE2.field4 FROM TABLE1 JOIN TABLE2 ON TABLE1.field2=TABLE2.field2 WHERE TABLE1.field2=2;
hi try the following as ur query.
It is not preferred all the time to use * in the select query
SELECT T1.field1,T1.field2,T1.field3, T2.field4 FROM TABLE1 AS T1 INNER JOIN TABLE2 AS T2 ON T1.field2=T2.field2 WHERE field2 = 2

Categories