select multiple tables mysql - php

I am trying to select two tables with where clause,
The problem: I am getting more than 2 result. something like 123451111 I only have two ids with the value 1. I think I am doing it wrong.
The tables don't have the same structure and are not related by any means. Any ideas?
<?php include_once("config.php");
$s = '1';
$stmt =$mydb->prepare("select * FROM table1,table2 where table1.id = ? or table2.id = ?");
stmt->bind_param('ss', $s, $s);
echo $mydb->error;
$stmt->execute();
?>
<?php
$results = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
echo $row['id']."<br/>";
}
?>

You need to have a join between table1 and table2 on some unique column, say id.
select * FROM table1,table2 where table1.id = table2.id;
Additionally you can have multiple filter conditions( say you want to filter the tables on id=101 -
select *
FROM table1,table2
where table1.id = table2.id
and table1.id = 101;
Hope this helps. Whenever you have multiple tables in a SQL statement, you need to join them otherwise the engine would make cartesian product as it happens in Cartesian product of mathematical set theory.
Basically you should have at least n-1 join conditions where n is the number of tables used.

Your question is a little problematic, but if your problem is not getting two id's, but you are getting one correctly with the use of a JOIN, you may be looking for a IN clause:
SELECT *
FROM table1,table2
WHERE table1.id = table2.id
AND table1.id IN (ID1, ID2);
Using IN instead of = lets you match multiple values to the table.id. This way, you get data from both tables and you get both ID's

This is join usage :
select t1.*,t2.* FROM table1 t1
left join table2 t2
on t1.id = t2.id
where t1.id = "keyword"

Related

Php how to use multi tables in one mysql query

So I have two tables in my phpmyadmin like
tabel1 and tabel2
in both tables, i want to select id = 2
so I have tried
mysql_query('SELECT * FROM tabel1, table2
WHERE id=2');
but not working plz give me some suggestions
You can use UNION ALL to accomplish what you want.
SELECT * FROM table1 WHERE id = 1
UNION ALL
SELECT * FROM table2 WHERE id = 1
Depending on your exact requirements, the query might be as easy as
SELECT *
FROM table1, table2
WHERE table1.id=2 AND table2.id=2
You are implicitly joining your tables for the condition of table1.id and table2.id being equal 2.
Use inner join and also read Manual
mysql_query('SELECT * FROM tabel1 as t1
inner join table2 as t2 on t1.id=t2.id
WHERE t1.id=2');
I think you have a typo there. You said you have table1and table2
Then your SQL statement should be
mysql_query('SELECT * FROM table1, table2 WHERE id=2');
instead of
mysql_query('SELECT * FROM tabel1, table2 WHERE id=2');
what was in your question.

How to search into table B if the result of searching into table A is zero?

I have three tables and I need to search in the first one, it there isn't any result, then search into second one and so on ..!
Here is my code:
// connecting to database
$stm1 = $this->dbh->prepare(" select * from table1 where col = :name; ");
$stm1->bindValue(":name", $name, PDO::PARAM_STR);
$stm1->execute();
$which_table = "table1";
// the result of searching into table1 is zero, then search into table2
if (!$stm1->rowCount()) {
$stm2 = $this->dbh->prepare(" select * from table2 where col = :name; ");
$stm2->bindValue(":name", $name, PDO::PARAM_STR);
$stm2->execute();
$which_table = "table2";
// the result of searching into table2 is zero, then search into table3
if (!$stm2->rowCount()) {
$stm3 = $this->dbh->prepare(" select * from table3 where col = :name; ");
$stm3->bindValue(":name", $name, PDO::PARAM_STR);
$stm3->execute();
$which_table = "table3";
// the result of searching into table3 is also zero
if (!$stm3->rowCount()) {
$which_table = 'none of them';
}
}
}
My code works as well, But it is slow, How can I optimize it and make it faster? As you see, there is three separated query and multiple if-statement .. How can I reduce them? Generally How can I improve that code? Can I do that using pure-sql?
If you code is slow, then you probably just need indexes:
create index idx_table1_col on table1(col);
create index idx_table2_col on table2(col);
create index idx_table3_col on table3(col);
With indexes, you can also phrase the query as a single statement, assuming the columns in the tables are the same:
select t1.*
from table1 t1
where t1.col = :name
union all
select t2.*
from table2 t2
where t2.col = :name and
not exists (select 1 from table1 t1 where t1.col = :name)
union all
select t3.*
from table3 t3
where t3.col = :name and
not exists (select 1 from table1 t1 where t1.col = :name) and
not exists (select 1 from table2 t2 where t2.col = :name);
This is a more complex query, but your code would only require a single query. And, with indexes, it should be very fast.
My code works as well, But it is slow, How can I optimize it and make it faster?
Add index for the column col
By the way, you may add limit 1 to your queries. It'll help you you have zillions of values in your tables to match

PHP/MySQL select query to go through four related tables in database

I have a select query and an insert query as follows:
$select_query = mysql_query("SELECT trees, animals FROM Table1 WHERE gardens > '10000'", $mysql_connection);
while ($row = mysql_fetch_array($select_query)) {
$trees = $row['trees'];
$animals = $row['animals'];
$names = ?????????? // in order to get the names, a select query should go through Table2 and Table4
//and finally get the assigned names from Table3. Please see the schematic picture of tables.
$insert_query = mysql_query("INSERT INTO table6 (new_trees, new_animals, new_name) VALUES ('$trees', '$animals', '$names')", $mysql_connection); }
I want to select and insert the $trees, $animals and $names into another table. There is no problem with $trees and $animals variables, but I do not know how to select the data for $names. As it is seen in the schematic picture of tables, Table1.id=Table2.reference and Table2.first_id gets values from Table4.id.
Then, Table4.second_id gets values from Table3.id and finally Table3.name must be selected in order to satisfy the $names variable in above-mentioned $insert_query. Sorry if I did not explain the problem more clearly. Could you please review the picture and let me know your solution?
Lookup the JOIN clauses:
SELECT
t1.id, t1.trees, t1.animals, t3.name
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t2.reference = t1.id
LEFT JOIN table4 AS t4
ON t2.first_id = t4.id
LEFT JOIN table3 AS t3
ON t4.second_id = t3.id
WHERE // Your select conditions

Selecting data from mysql table and related data from another to join them

Ive looked at other questions and answers but still dont understand which brings me here.
I have one data base two tables. lets say table1 and table2 from database.
I'm looking to grab all the information from table1 and only one column from table2 that coincides with the correct row in table1.
Example which I know is wrong:
SELECT table1.*, table2.time_stamp FROM table1, table2
WHERE table1.ticket_id=$var AND table1.user_id = table2.user_id
Basically select data from table1 then use a value from the selected table to grab the related data from table2 and join them to output them as one mysql_query. Im sure its simple and has been asked before.
edit:
I dont receive an error. SQL just returns noting. log form of this would be:
$sqlResults = mysql_query("SELECT table1.* FROM table1 WHERE table1.ticket_id=$var")
while($rowResult = mysql_fetch_array( $sqlResults )) {
$userID = $rowResult['user_id'];
$sqlResults2 = mysql_query("SELECT table2.time_stamp FROM table2
WHERE table2.user_id=$userID")
}
I want to combine that into one sql statement so i dont have to hit table2 for every row table1 has
Use a JOIN to bind the rows from table2 to those from table1:
SELECT t1.*, t2.time_stamp FROM table1 t1
JOIN table2 t2 ON t1.user_id = t2.user_id
WHERE t1.ticket_id=$var

Help with grasping (INNER?) JOIN

I'm having trouble building a query. I can do what I want in 3 different queries.
SELECT id FROM table1 WHERE url LIKE '%/$downloadfile'
put that in $url_id
SELECT item_id FROM table2 WHERE rel_id = '$url_id'"
put that in $item_id
SELECT rel_id FROM table2 WHERE rel_id = '$item_id' AND field_id = '42'"
put that in $user_id
But from reading examples on joins and inner joins I think there's a more elegant way. I cant wrap my brain around writing a better query (but would like to) I can describe how it should go:
table1
fields: id, url
table2
fields item_id, rel_id, field_id
I know the last part of table1.url (LIKE '%/$filename') with that I select table1.id.
table1.id is equal to one entry in table2.rel_id. So get that and select the table2.item_id.
In table2 there is another entry which has the same table2.item_id and it will have a table2.field_id = '42'
And finally the value I need is the table2.rel_id where the table2.field_id was 42.
I will fetch that value and put it in $user_id
Can this be done with one query using joins/inner joins?
SELECT url, second.rel_id AS user_id
FROM table1
INNER JOIN table2 AS first
ON table1.id=first.rel_id
INNER JOIN table2 AS second
ON first.item_id=second.rel_id
WHERE second.field_id='42'
AND table1.url LIKE '%/:downloadfile'
Sure, should be something like:
SELECT t2_second.rel_id
FROM table1 t1
INNER JOIN table2 t2_first ON t1.id = t2_first.rel_id
INNER JOIN table2 t2_second ON t2_second.rel_id = t1_first.item_it
WHERE
t1.url = '%/:filename' AND
t2_second.field_id = 42
You could even throw in a distinct so that each t2_second.rel_id is only returned once:
SELECT DISTINCT [...]
You might not need this, however, if t2_second.field_id = 42 will restrict the query to only return one row for each t2_second.rel_id
This the query that works for me, made one small change to Ignacio's answer:
SELECT url, second.rel_id AS user_id
FROM table1
INNER JOIN table2 AS first
ON table1.id=first.rel_id
INNER JOIN table2 AS second
ON first.item_id=second.item_id
WHERE second.field_id='42'
AND table1.url LIKE '%/:downloadfile'

Categories