Join tables - MySQL & PHP - php

I'm trying to join two tables. The first table has a list of 11 items which are 'site_names' with an auto id field of 'id'. The second table that I want to connect has an auto id field of 'desc_id' and another field of 'descriptions'. This second table currently has 3 rows of data that I want displayed only for id 1 in table 1.
So, I want to accomplish is to connect the first site in table one with an id of '1' to the entire second table.
I can't seem to figure out how connect only the first entry(id=1) in table 1 to all the rows in table 2 (tb.1->id->1 to tbl.2->desc_id->1,2,3).
I hope that made sense. Any help would be great. Thanks

Try:
select site_name, descriptions
from table_1
inner join table_2
on 1 = 1
where table_1.site_id = 1
This should join give you what you want.
OK - based on the comment, I'm guessing what you want is:
site1 | desc1 | desc2 | desc3
all on one row. This is a bit trickier - particularly if you want it to remain open to an arbitrary number of descriptions. For just 3 (or, really, any limited subset, but as the number goes up, it gets ugly), you could do:
select site_name, t2.desc, t3.desc, t4.desc
from table_1
inner join table_2 t2
on t2.desc_id = 1
inner join table_2 t3
on t3.desc_id = 2
inner join table_2 t4
on t4.desc_id = 3
where site_id = 1
This kind of stuff is highly irregular though. It seems to me like something about your schema is probably not quite right to generate this sort of requirement.

Here is the query:
<?php
$mysql = new mysqli('localhost', 'root', 'root') or die('counld not connect');
$result = $mysql->query("SELECT ajax_demo.explore.site_name, anthony1.property.descriptions FROM ajax_demo.explore INNER JOIN anthony1.property ON ajax_demo.explore.id = anthony1.property.desc_id") or die($mysql->error);
if($result)
{
while($row = $result->fetch_object())
{
$id = $row->id;
$siteName = $row->site_name;
$siteDescription = $row->site_description;
echo "$siteName";
echo "$siteDescription";
}
}
?>

I may be missing something here, but it sounds to me like you need to add a foreign key to the Site table. If I understand your question correctly, your tables should look something like this:
Site
- SiteID
- DescriptionID
- SiteName
Description
- DescriptionID
- Description
Then your query to get Sites and their associated Descriptions would look like this:
SELECT
s.SiteName,
d.Description
FROM
Site s INNER JOIN Description d
ON s.DescriptionID = d.DescriptionID
This table structure assumes that multiple Sites share single Descriptions (as per your posted question).

Related

Update value from one database to another database - fastest method

I have two tables.
first datatable structure has nine columns but the important three are:
code | name | value
2D3 | name test | 0.12
the second table has the same three columns.
Now I want to update all rows of the first table with the values of table two where code AND name are the same as in table two.
So my current idea is to do a select of all rows of table 1 with the code and name columns, than check if a row with the same code and name exists in table 2, if yes get that value and do a UPDATE query in table 1 with value of table 2.
The problem is that the two tables are hugh and I am sure that I am not using the fastest method.
anyone an idea for the fastest method to do this? Thank you very much!
EDIT: the query:
$getall = "SELECT code, name, value FROM table2";
$query = mysqli_query($conn, $getall );
while($result = mysqli_fetch_array($query))
{
$UpdateAll = "UPDATE table1 SET value = '".mysqli_real_escape_string($conn,$result["value"])."' WHERE name = '".mysqli_real_escape_string($conn,$result["name"])."' AND code = '".mysqli_real_escape_string($conn,$result["code"])."'";
$result2 = mysqli_query($conn, $UpdateAll); }
You speak of two databases but really mean two tables, don't you? In this case, you can do it with one update using a join, like this:
update table1 t1
inner join table2 t2 on t2.code = t1.code and t2.name = t1.name
set t1.value = t2.value;

MySQL very simple join example requested with subtable

I keep falling back into questions with MySQL joining.
And I would like to request a very simple example I could use to continue my journey of understanding learning the MySQL syntax.
Let's say I got the following table's
test_testtable
testtable_id
testtable_name
testtable_user
testtable_option
testtable_textfield
test_testlink
testlink_id
testlink_link
testlink_address
test_address
address_id
address_name
address_phone
address_email
address_street
address_city
address_zip
I would like to make a selection like :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
AND
JOIN `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Hence the linking structure is like:
test_testtable.testtable_id = leading
table test_testlink is a table to link the table test_testtable and test_address
And linking table test_testlink uses the field testlink_link to link to the table test_testtable, and uses the field testlink_address to link to the table test_address
This does not work. FOR ME.. Since I continuously seem to fail of catching the correct syntax logic.
So I hope that someone could give me a small example of how to correctly implement such a simple yet critical query!
TIAD!!
A general approach :
SELECT table1.* FROM table1
JOIN table2 ON table2.id_table1 = table1.id
JOIN table3 ON table3.id_table2 = table2.id
WHERE table1.id = 10
For your purpose :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testlink` ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
JOIN `test_address` ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Please read the reference
You are using wrong syntax. You should mention which tables to join first then based on which fields.
SELECT * (lets say I would define the fields) FROM `test_testable`
INNER JOIN test_testlink
ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
INNER JOIN `test_address`
ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
AND `test_testtable`.`user_id` = 5
select * from testlink JOIN testtable ON testlink.tableid = testtable.ID
JOIN testaddress ON testlink.addressid = testaddress.ID
WHERE testtable.ID = 5

Selecting data from a table based on conditions with other tables

I'm really unsure how best to go about writing this query. I have 3 tables and I need to run a query pulling data from one, based on conditions in the others.
Tables: surveys, survey_countries, survey_categories
surveys:
id | survey_id | network_id
survey_countries:
id | survey_id | network_id | country
survey_categories:
id | survey_id | network_id | category
(The survey_id in survey_countries and survey_categories relates to the survey_id column in the surveys table as opposed to the id column).
I need to retrieve data from surveys for a specific country and a specific category. Then I need to be able to UNION for other categories, but I guess I can do that later. My attempt:
SELECT surveys.*
FROM survey_countries
LEFT JOIN surveys ON survey_countries.survey_id = surveys.survey_id ANd survey_countries.network_id = surveys.network_id
LEFT JOIN survey_categories ON survey_countries.survey_id = surveys.survey_id AND survey_categories.network_id = surveys.network_id
WHERE survey_countries.country = 'GB'
AND survey_categories.category = 'my_category'
GROUP BY surveys.id
Thanks!
EDIT: the following seems to work:
SELECT s.*, ca.category, co.country
FROM surveys s
LEFT JOIN survey_countries co ON s.survey_id = co.survey_id AND s.network_id = co.network_id
LEFT JOIN survey_categories ca ON s.survey_id = ca.survey_id AND s.network_id = ca.network_id
WHERE ca.category = 'uncategorised'
AND co.country = 'GB';
I'm just not sure it's the best way to do it since I need to grab surveys with multiple categories later on?
Without example data and an example output, helping you on this query is very difficult. However..... your 2nd join relates survey_countries with surveys. I think you mean to join it to the survey_categories. Also, you have a Group By, with no aggregate functions. Get rid of it until you have too much information an need to summarize columns
I am not saying this is correct, but it is slightly more 'correct' than yours
SELECT surveys.*
FROM survey_countries
LEFT JOIN surveys
ON survey_countries.survey_id = surveys.survey_id
AND survey_countries.network_id = surveys.network_id
LEFT JOIN survey_categories
ON survey_categories.survey_id = surveys.survey_id
AND survey_categories.network_id = surveys.network_id
WHERE survey_countries.country = 'GB'
AND survey_categories.category = 'my_category'
(If you can, load up a schema and sample data in sqlfiddle. It will make this problem easier to solve.)

trying to output the correct value from SQL query from comparing a different table

I'm very new with SQL and need assistance on how I can accomplish this task using the correct query.
I have 2 tables that I need to use. Table "TB1" has:
id Name
1 bob
2 blow
3 joe
table "TB2" has:
compid property
1 bob
2 blow
I am trying to get which compid is missing in "TB2" and insert it from "TB1"
the query I am doing is:
SELECT id, name from TB1, TB2 where id <> compid
what I get is 2 ouputs of Id 1, and 2, and 3 outputs from id 3. by using php:
for($i=0;$i <= mysql_num_rows($comp)-1; $i++)
{
echo mysql_result($comp, $i, 0)."<br>";
}
and I expected the ouput 3 but instead got this:
1
1
2
2
3
3
3
I understand its comparing all the rows within the table but is there a way to achieve what I am looking for?
Thanks for your time.
You are performing an implicit Cartesian JOIN which results in every row against every other row. You need to specify what attribute JOINs the two tables.
Using implicit syntax (not recommended):
SELECT id, name
FROM TB1, TB2
WHERE id <> compid
AND TB1.Name = TB2.property <-- Column join
Using explicit syntax:
SELECT id, name
FROM TB1
JOIN TB2
ON TB2.property = TB1.Name <-- Column join
WHERE id <> compid
To accomplish your goal you would need something along the lines of:
SELECT TB1.id, TB1.name
FROM TB1
LEFT JOIN TB2
ON TB2.property = TB1.Name
WHERE TB2.compid IS NULL
See it in action
It's best practice to always alias the columns you select to prevent ambiguity.
To select it you can do:
SELECT *
FROM TB1
WHERE id NOT IN (
SELECT compid
FROM TB2
);

Group data from 2 table in mysql

Sorry, guys.I am quite new in mysql but I do need help from getting and merging data from 2 tables.
table_a
ID | TITLE | CONTENT | DATE
table_b
ID | POST_ID | IMAGE
Here's my code
$query = "SELECT table_a.*, table_b.IMAGE FROM table_a
LEFT JOIN table_b
ON table_a.ID = table_b.POST_ID
ORDER BY table_a.DATE";
$mysql_result = mysql_query($query);
$result = array();
while ($row = mysql_fetch_assoc($mysql_result)) {
$result[] = $row;
}
print json_encode($result);
However, for those record in table_a which got more than 1 IMAGE, my json contain duplicated CONTENT with different IMAGES.
Is there any methods to merge IMAGE with the same ID into a single record?
Thanks for any helps!
You can use the GROUP_CONCAT function to group the images as a comma-delimited list in one column of your posts table.
If I understand correctly, you want to have all fields from table_a, and only one (maybe combined) field from table_b.
First of all, you have to decide what you want to get, if you have more than one image:
Only 1 image? Use MIN(table_b.IMAGE) or MAX(table_b.IMAGE) in the
following SQL
All images separated by e.g. a comma? Use GROUP_CONCAT(table_b.IMAGE SEPARATOR ',') or similar in the following SQL
Next you have to understand, that to get only one row per table_a.ID, you have to group by table_a.ID, so we have
SELECT
table_a.*,
<function from above> AS image
FROM table_a
LEFT JOIN table_b
ON table_a.ID = table_b.POST_ID
GROUP BY table_a.ID
ORDER BY table_a.DATE
I believe what you need is something like this:
SELECT table_a.*, GROUP_CONCAT(table_b.IMAGE) FROM table_a
LEFT JOIN table_b ON table_a.ID = table_b.POST_ID
GROUP BY table_a.*
ORDER BY table_a.DATE
(Not sure if you have to spell out the GROUP BY clause, listing field names individually, or whether .* notation will be accepted here.)
You can perhaps use JOIN instead of LEFT JOIN . In this way it will only load one row
or the other way
put GROUP BY a.ID jsut before ORDER BY...

Categories