Basically I have 2 SQL queries from 2 different databases and I am trying to compare where they are equal and then join together the other information for that value. My first query contains an id and a product name, my second query contains a product name and components. So I'm trying to join them on the product name and then show the other two bits of information with them. The db I selected is being used in the second query. Any idea what I should do?
So far I have this, which only seems to show one result:
$catid = mysql_query("Select a.entry_id, b.cat_name from blog.exp_category_posts a inner join blog.exp_categories b on a.cat_id=b.cat_id where b.Group_ID = 3");
$results = mysql_query("Select a.name, c.product from wr_scientific a inner join wr_scientific_products b on a.id=b.scienc_id Join xcart_products c on b.prod_id=c.productid LIMIT 1000");
while($row1 = mysql_fetch_array($catid)){
$row2= explode("™", $row1['cat_name']);
$row3= explode("®", $row2[0]);
while($row = mysql_fetch_array($results)){
$rowpro = explode("™", $row['product']);
$rowprod = explode("®", $rowpro[0]);
if($rowprod[0] == $row3[0]){
echo $rowprod[0].$row['name'].$row1['entry_id'];
}
}
}
Thanks for any help
If the two databases are located on the same instance of MySQL (~ same machine), then you can refer to a table in say db2 from (say) db1 by prefixing the table name with the database name.
E.g:
USE db1 ;
SELECT
db1.table_in_db1.id, -- you can specify the database name here, but
table_in_db2.id, -- there is no ambiguity, the database name is optional
field_in_table_in_db2 -- the same way the table name is optionnal when there is no ambiguity
FROM
db1.table_in_db1 -- database name is optionnal here, current database is assumed
JOIN
db2.table_in_db2
ON ...
Related
I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!
I have two databases and I am trying to compare two tables. My code does not seem to be working, not sure what I am doing wrong.
Here is the code.
<?php
include 'connection.php';
/*
* This code compares between two tables
*/
//SQL call
$getData = $connection->prepare("SELECT `CustomerCity` FROM `auth` LEFT JOIN `tb_data.cobs.city` WHERE `CustomerCity` = `tb_data.cobs.city` LIMIT 3");
$getData->execute();
$gotData = $getData->fetchAll(PDO::FETCH_ASSOC);
print_r($gotData);
In my database I have two tables, on is cobs, the other is tb_data. tb_data has a table called cobs and auth is a table within a database called d_data. Both of these tables have a city column. I need get every record in auth that has a city that matches in the cobs table.
That looks like the query is using a mixture of explicit join syntax with obsolescent syntax for the join using the WHERE clause for the join conditions.
If so try:-
SELECT CustomerCity
FROM auth
LEFT JOIN tb_data.cobs
ON auth.CustomerCity = cobs.city
LIMIT 3
Others have pointed out that your query is wrong, but have not provided a correct answer. This is what you are likely looking for:
SELECT `auth.CustomerCity` FROM `auth`
LEFT JOIN `tb_data.cobs` ON `tb_data.cobs.city` = `auth.CustomerCity`
LIMIT 3
Try this :
Select *.auth, *.cobs from auth join cobs on auth.city = cobs.city limit 3
The query is incorrect, you need to specify the link betweeen the tables auth and tb_data.cobs.city. For example:
SELECT
*
FROM
FOOTABLE FOO
LEFT JOIN
BARTABLE BAR ON BAR.FOO_ID FOO.ID = -- here goes the link between them
WHERE
...
I am trying to echo both the employee name and manager name
SQL QUERY:
SELECT *
FROM `form`
INNER JOIN `emp` AS employee
ON `form`.emp_ID = employee.emp_ID
INNER JOIN `emp` AS manager
ON `form`.manager_ID = manager.emp_ID
ECHO:
while($row = $result->fetch_assoc()){
echo $row['emp_name'];
}
Always outputs the managers name.
have tried the following:
$row['employee.emp_name']
$row['employee']['emp_name']
which all don't work.
any help is appreciated
When the columns have the same name, their values will overlap when retrieving by fetch_assoc(). You can either use fetch_array() and reference the columns by numeric index (not recommended with SELECT *, since you can't easily guarantee the order of columns), or you will have to list the column names explicitly and alias them. For example:
SELECT emp.emp_name emp_emp_name, manager.emp_name manager_emp_name, ...
This would give you separate distinctly named fields in the result, that you could then access from what fetch_assoc() returns.
I have made an SQL query from two tables. Everything works good but problem is that this two tables have the same field names and after I do not know how to display them correct, how to tell that $data['aaa'] is from table 1 and the same $data['aaa'] from table 2
here is my SQL query :
$query_str = "SELECT
cm.id,
cm.global_category_id,
cm.num,
cm.menu_lv,
cm.menu_ru,
cm.menu_en,
u.id,
u.menu_lv,
u.menu_ru,
u.menu_en
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";
and display data
<? foreach ($sub_category_list as $line) : ?>
<tr>
<td><?=$line['menu_lv']?></td> <---- here I want to display data from products_global_category u
<td><?=$line['sub_menu_lv']?></td> <---- products_category cm
<td><?=$line['sub_menu_ru']?></td> <---- products_category cm
<td><?=$line['sub_menu_en']?></td> <---- products_category cm
</tr>
<? endforeach; ?>
As a solution you can change your SQL query to give an alias to the fields that have the same name.
For example:
SELECT somefield AS othername FROM table.
In this case, the somefield field will be available through the alias othername.
In your case:
$query_str = "SELECT
cm.id AS cm_id,
cm.global_category_id,
cm.num,
cm.menu_lv AS cm_menulv,
cm.menu_ru AS cm_menuru,
cm.menu_en AS cm.menuen,
u.id as u_id,
u.menu_lv AS u_menulv,
u.menu_ru AS u_menuru,
u.menu_en AS u_menuen
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";
And then in your PHP:
$line['u_menulv'] //Access field menu_lv from products_global_category table
$line['cm_menulv'] //Access field menu_lv from products_category table
EDIT: In mysql_fetch_array documentation page:
If two or more columns of the result have the same field names, the
last column will take precedence. To access the other column(s) of the
same name, you must use the numeric index of the column or make an
alias for the column. For aliased columns, you cannot access the
contents with the original column name.
In other words, either create an alias like shown above or access the fields by the numeric index of the array.
Simply alias the records you wish to print out which conflict with one another, for example:
SELECT
table1.pid AS page_id,
table2.pid AS product_id
FROM
table1
LEFT JOIN
table2
ON
table1.id = table2.id
And then within your PHP you can echo them out as follows:
while ($row = mysql_fetch_assoc($res)) {
echo $row['page_id'];
echo $row['product_id'];
}
Hope this helps!
I have 3 tables I need to join. The contracts table is the main table, the 'jobs' and 'companies' table are extra info that can be associated to the contracts table.
so, since I want all entries from my 'contracts' table, and the 'jobs' and 'companies' data only if it exists, I wrote the query like this....
$sql = "SELECT * FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
ORDER BY contracts.end_date";
Now how would I output this in PHP? I tried this but kept getting an undefined error "Notice: Undefined index: contracts.id"...
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
if(mysql_num_rows($sql_result) > 0){
while($row = mysql_fetch_array($sql_result))
{
$contract_id = stripslashes($row['contracts.id']);
$job_number = stripslashes($row['jobs.job_number']);
$company_name = stripslashes($row['companies.name']);
?>
<tr id="<?=$contract_id?>">
<td><?=$job_number?></td>
<td><?=$company_name?></td>
</tr>
<?
}
}else{
echo "No records found";
}
Any help is appreciated.
The column names will not be prefixed like this - and with each table having a column called "id" you could be in trouble. You should explicitly identify the columns you want returned rather than using "select *", and you then just retrieve the column by name un prefixed (e.g. $row['job_number']).
The below would solve you problem.
$sql = "SELECT contracts.id AS contract_id, jobs.job_number, companies.name FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
ORDER BY contracts.end_date";
Your problem is likely to be realted to the fact you are using two tables with the field id this is why you should select them as an alias using the mysql as clause.
You may also want to look into using a naming convention for your fields and sticking with it. For example, check out the theory of Hungarian Notation, this would stop issues like this from arrissing.