Group data from 2 table in mysql - php

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...

Related

How can I select a row that may contain swapped fields?

How can I select one row from that table http://i.stack.imgur.com/27cu9.jpg where values of 'user_1' and 'user_2' may look like
user_1 user_2
1 2
2 1
In other words I want to select a field that contains 2 users with submitted=1 no matter in which field the value is.
Here is a simple query that does this:
select *
from t
where submitted = 1 and 2 in (user_1, user_2)
If I understood your question, I think you need to JOIN the table on itself if you are trying to return rows that have corresponding users (1,2) and (2,1):
select t1.*
from yourtable t1
join yourtable t2 on
t1.user_1 = t2.user_2 and t1.user_2 = t2.user_1
SQL Fiddle Demo
If however you are just trying to see if user 2 exists in either of the fields, then look at Gordon's post.
Use this:-
select * from tblname as t1, tblname as t2 where
t1.user_1 = t2.user_2 and t1.user_2 = t2.user_1 and t1.user_1<>t1.user_2
EDIT:-
Updated the query so that the rows with the same values do not appear in the result.

SQL Query for a one to many relationship

I have two tables, Table A and Table B. For each record in table A there are many records in Table B; thus, a one to many relationship exists between tables A and B. I want to perform a query so that for each row returned from table A, all of the corresponding rows will be returned from table B. From what I understand I'll need to use a INNER Join - however, how would I go about accessing all of the returned rows through say, PHP?
$sql = "Select A.ID, B.Name * From A INNER JOIN B ON A.ID = B.ID";
A.ID | B.fName | B.lName
1 nameone lnameone
1 nametwo lnametwo
2 namethree lnamethree
4 namefour lnamefour
Now that I have the above results, I want to use PHP to loop through all of the values of B.Name only for a single A.ID at a time. So, the results I want would look like:
1.
nameOne lNameOne
nameTwo lnametwo
2. namethree lNamethree
4. nameFour lNameFour
Basically, I'm trying to group the query results by the ID in table A.
I appreciate the help very much!
Thank you,
Evan
You could just Google "php get from database," and use some normal array pre-processing, but I worry the advice you find may not be ideal. Here's what I'd do:
$pdo = new PDO('mysql:host=host;dbname=dbname', 'user', 'pass');
$result = $pdo->query(<<<SQL
SELECT
ID,
Name
FROM
A
-- Alternative to `JOIN B USING(ID)` or `JOIN B ON (A.ID = B.ID)
NATURAL JOIN B
SQL
);
$a = array();
while ($row = $result->fetch()) {
if (!isset($a[$row['ID']]) {
$a[$row['ID']] = array();
}
$a[$row['ID']][] = $row['Name'];
}
You could also GROUP BY the ID and GROUP_CONCAT the names to be exploded in PHP later to skip the manual array creation and reduce some iteration (although SQL will do more in that case).
Adding a simple ORDER BY A.ID to the SQL query would probably get you quite far in "grouping" the items together. It's difficult to give a more detailed answer without knowing exactly what you want to do with the "groups".

Selecting rows from a table by One a field from other table

What i want, to display rows from a table which is selected by a field from other table single value, lets say to display images from a table by last category id.
I have this type of query, but this return me all matching keys rows, if i inset LIMIT 1 then it return one row...
SELECT i.prof_image FROM profile_images i
JOIN images_cat cat ON (cat.cat_id = i.cat_id)
GROUP BY i.prof_image;
//OR LIMIT 1;
Any idea to fix this problem. (i.e. displaying the latest category images)?
This will work for your specific example.. If you need to be more selective, then please post some more details..
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
SELECT * FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.id
This query will grab all things in table_2 that have the same id value.
Note that it is a LEFT JOIN - which means that if there are no matching values in table_2, it will still return the values from table_1.
What is your intent with using last()?
Hope this helps.

is it possible to use one mysql query to achieve this?

I am hoping for some help making my queries more efficient if possible. I have two tables. One which contains the types of content available and another which contains content linked to the type table by a type id.
I am trying to select from the content table and group the results by type_id. I am currently using a query inside a loop to do this so it is selecting again from the second table for each type_id. Is there a better/more efficient way to do this?
Here are my current tables and queries:
type_id type
1 type 1
2 type 2
id title type_id content
1 test1 1 test content 1
2 test2 2 test content 2
3 test3 1 test content 3
$query="select type_id, type from type_table";
foreach($query as $type){
$query="select title, content from content_table WHERE type_id=$type['type_id']";
}
I hope this makes sense.
Thanks
Your example appears to select all possible values from the content table, albeit in batches of a given type at a time. So select title, content from content_table would surely do this whole thing in one go, without looping.
To put each type_id into a new div, you could do something like this:
SELECT title, content, t.type_id, t.type
FROM content_table c
JOIN type_table t ON t.type_id = c.type_id
ORDER BY t.type_id
// pseudo-code
prev_type_id = -1
print "<div>"
foreach row:
if type_id != prev_type_id:
prev_type_id = type_id
print "</div><div>"
print "</div>"
(edited based on comments)
Use a join and order by. Something like (no guarantee for syntactical correctness):
SELECT
c.title, c.content, t.type_id, t.type
FROM
type_table t, content_table c
WHERE
c.type_id = t.type_id
ORDER BY
t.type_id
Sure, you could join the two tables.
In this example, however, it doesn't appear that you even need to use the type_table. You could just sort your query by type_id:
select title, content from content_table order by type_id;
What is the expected result ?
This is what I think you want.
$sql = 'SELECT t.type, c.title, c.content
FROM `content_table` c
INNER JOIN `type_table` t ON c.type_id = t.type_id
ORDER BY c.type_id ASC'
// Dont use a foreach-loop to loop over the results. While-loop is ideal
while ($row = <query or fetch from resultset here>) {
..
}

Join tables - MySQL & 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).

Categories