Fetch data from multiple MySQL tables - php

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

Related

SQL Query Count across 2 tables

Here is what I have (i am including only the relevant cells to each table)
table1:
- user_id
table2:
- id
- manager_id
... and I have a PHP variable
$manager_id
So, what I am trying to do is get a COUNT(*) of how many records exist in table1, but the record should only be counted if table1.user_id (which is the table2.id) has a table2.manager_id == $manager_id
So, the only way I know how to do this would be to do something like this in PHP (which is wildly inefficient):
$query = "SELECT user_id FROM table1 WHERE {my where clause}";
// execute query and place into $item[] array (not shown for brevity)
foreach ( $item as $user_id ) {
$query = "SELECT manager_id FROM table2 WHERE id = '{$user_id}';
// execute query, place each item into $row
if ( $row['manager_id'] == $manager_id ) {
// tick up count by 1
}
I am fairly certain there is a way to do this purely in SQL, but I am at a loss.
You could try the below query:
select count(1) from table1 t1, table2 t2 where t1.user_id = t2.id and t2.manager_id = ?
you need to set your where clause to have this condition i.e.
SELECT Count(user_id) FROM table1 where
table1.user_id = table2.id
AND Convert('Varchar', table2.manager_id) = $manager_id
I assume your php variable $manager_id has a string
if it is not a number then there is no need to convert the sql column (table2.manager_id) to varchar.
You can do this with one SELECT statement:
SELECT COUNT(*)
FROM table1
WHERE user_id IN (
SELECT id
FROM table2
WHERE manager_id = <your-value-of-manager-id>
)
In case you need to use the data and want to count on PHP side you can use the following SELECT statement using a LEFT JOIN:
SELECT table1.*
FROM table1 LEFT JOIN table2 ON table1.user_id = table2.id
WHERE table2.manager_id = <your-value-of-manager-id>
To execute the SELECT statements you should use prepared statements (using PDO or mysqli).
example using the first query:
$sql = 'SELECT COUNT(*) FROM table1 WHERE user_id IN (SELECT id FROM table2 WHERE manager_id = ?)';
$sth = $dbh->prepare($sql);
$sth->execute([$manager_id]);
$rows = $sth->fetchAll();
if (count($rows) === 1) {
echo $rows[0][0];
}
example using the second query:
$sql = 'SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.user_id = table2.id WHERE table2.manager_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute([$manager_id]);
$rows = $sth->fetchAll();
echo count($rows);

PHP SQL get data from 2 tables and output wanted information

i am trying to achieve the following result. (i am sorry for the horrible explanation but i find it very hard to explain :P)
I need data from 2 tables.
Table1
id, table2_id, user_id
Table2
id, Name
Table1 example information
ID 1 Table2_id 1 user_id 3
ID 2 Table2_id 2 user_id 3
ID 3 Table2_id 5 user_id 3
Table2 Example Information
ID 1 Name TEST
ID 2 Name Hello
ID 3 Name Helpme
ID 4 Name Please
ID 5 Name IamLost
i Would like to output everything tied user_id 3. This would be my ideal end result
TEST
Hello
IamLost
I have this as code
$id = "3";
$sth = $db->prepare("SELECT table2_id, user_id, naam FROM table1, table2 where user_id = $id ");
$sth->execute();
$result = $sth->fetchAll();
foreach( $result as $row ) {
echo $row['table2_id'] . ' ';
echo $row['naam'] . '<br>';
}
But this just outputs everything but then twice. like this
TEST
TEST
Hello
Hello
Helpme
Helpme
Please
Please
IamLost
IamLost
A LEFT JOIN should do the trick:
SELECT `table1`.`table2_id`, `table1`.`user_id`, `table2`.`name`
FROM `table1`
LEFT JOIN `table2`
ON `table1`.`Table2_id` = `table2`.`id`
WHERE `table1`.`id` = $id
MySQL JOIN Syntax
Use Joins in SQL.
The SQL Query should look like this:
SELECT T1.USER_ID, T2.NAME
FROM TABLE1 AS T1
JOIN TABLE2 AS T2
ON T1.TABLE2_ID = T2.ID
WHERE T1.USER_ID = 3
these two table must be related to each other. When you select , returned rows should be equal this two tables. This why we use table joins e.g
SELECT a.user_id,a.table_id,b.name FROM table1 as a, table2 as b
RIGHT OUTER JOIN table 1
ON b.ID = a.table2_id
AND table1.user_id = 3
I believe you just need to be more precise:
$sth = $db->prepare("SELECT table2_id, user_id, name
FROM table1
LEFT JOIN table2
ON table1.Table2_id = table2.id
WHERE user_id = $id ");
A simple right outer join will help you here.
SELECT * FROM table2
RIGHT OUTER JOIN table 1
ON table2.ID = table1.table2_id
AND table1.user_id = 3

Retrieve data from one MySQL table and use it in another one

I have two tables i use in jqgrid.
Table 1: id->0,1,2; state->1,1,0
Table 2: id->0,1,2,3; product->apple,banana,cherry,melon;
I want to find the id's which have state 1 and retrieve the corresponding product from the other table. Is there a proper way to do it?
$result below always returns zero. I am connected to the database successfully.
Here is the code:
$var = "SELECT id FROM table1 WHERE state = 1";
$result = mysql_query($var);
$grid->setSelect('order', "SELECT id, product FROM table2 WHERE id='$result' ");
You can run one query:
SELECT t2.id, t2.product
FROM table2 t2
WHERE t2.id = (SELECT t1.id FROM table1 t1 WHERE t1.state = 1);
If the subquery could conceivably return more than one result, then use in instead of =:
SELECT t2.id, t2.product
FROM table2 t2
WHERE t2.id IN (SELECT t1.id FROM table1 t1 WHERE t1.state = 1);

PHP SQL Query Fields from Another Table Join

I am trying to get a query using fields from 2 tables.
I need to query Table1 but only Table2 has the variable venue_location that I need to query.
Basically I need to count all records on Table1 where Table1.venue_location = $MyVariable.
Here is what I've put together but I believe I need to use Joins for this?
Table1
- venue_id
Table2
- venue_id,
- venue_location
SELECT * FROM Table1 WHERE table1.venue_id = table2.venue_id and table2.location = '$MyVariable'
How can I do a query for this?
Use the power of join table
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
You can get back the count of rows with mysqli_num_rows() in PHP, or change le select by SELECT COUNT(*) AS nbRow FROM ... and check of value in nbRow column
You can join two tables on venue_id and then group it by venue_id where location is your $MyVariable.
Your final query will look like:
SELECT count(table2.venue_id)
FROM Table1
JOIN Table2 ON table1.venue_id = table2.venue_id
WHERE table2.location = '$MyVariable'
GROUP BY table2.venue_id
try this
SELECT Table1.venue_id, Table2.venue_location FROM Table1 INNER JOIN Table2
ON Table1.venue_id='$MyVariable';

Double tables select show?

I have a problem...I have 2 tables, Table1 and Table2.
Table1:
id,int(11)
text,varchar(11)
Table2:
id,int(11)
agentid,int(11)
unique(id,agentid)
Table2 has many id and agent ids in it. The data for the id in table 2 came from table 1.
I have an agentid say $aid. This has many id's associated with it in table 2.
I am trying to get the set of text values out from table 1 associated with all ids which are related to agentid $aid from table 2.
Does that make sense?!
Any ideas?
select text from table1 where id in
(
select id from table2 where agentid = <your aid>
)
This will give you all text rows for given agentid.
The same can be done using join too -
select t1.text from table1 t1
inner join table2 t2
on t1.id = t2.id
where t2.agentid = <your aid>
select * from table1 as t1 inner join table2 as t2
on t1.id = t2.id
where agentid = $aid
The query:
$sql = "select t1.text from table1 t1, table2 t2 where t2.id = t1.id and t2.agentid = {$aid}";
Try not to include the $aid directly in the query, but escape it and/or use prepared statements with query parameters.

Categories