I have an android application that has 2 tables, one table stores posts and the other table stores images of the posts incase it has an image, changes are not all posts will have images, if a post has an image its primary key will be stored in the foreign Key table, when loading the posts I have to get all posts wether with image or not then check in the image table to see which posts have images and add the images to the posts below is a graphical overview of my tables
Post Table
`|post_id |post | post_description|
|--------|-----|-----------------|
| | | |`
Image Table
`|img_id |fk_postID | imagePath |
|--------|----------|-----------------|
| | | |`
I could have used a join like
Query = "SELECT post_id, post, post_description, imagePath FROM PostTable,
ImageTable, Where PostTable.post_id = ImageTable.fk_postID;
but this query is only returning posts with images and forgeting about posts without images, How can I get all posts be it with image or not? Thanks in advance.
ok, you asked, so give this a whirl, see if you like the output
SELECT pt.post_id, pt.post, pt.post_description, im.imagePath
FROM PostTable pt
left join ImageTable im
on im.fk_postID=pt.post_id
It will bring along for the ride the right table (ImageTable) of those posts that don't have images.
Uses table aliases (pt and im). That helps to be explicit which table the columns come from on the first line in case there are common column names in both, plus a little less typing.
Untested
reference Mysql Left Joins
Try using Left join and that will result all entries from left table and matched entries from right table.
SELECT posttable.postid,posttable.post,posttable.postdescription, imagetable.imageid,imagetable.fkpostid,imagetable.imagepath
FROM posttable
LEFT JOIN imagetable
ON posttable.postid=imagetable.fkpostid
ORDER BY posttable.postid;
Code should look like that.
http://www.w3schools.com/sql/sql_join_left.asp
Related
I have a requirement for a PHP function that takes table or tables and the required columns from those db tables and returns a html table containing the data. I know how to do this for one table but am struggling with how to make this more dynamic
My thinking for one table would be to have a function that takes the table name and then an array of columns and then just selects the data from the table and then loops through it constructing the data as html and then return that from the function.
As an example my database has two tables; users and orders
users
|----------------------------|
|user_id|first_name|last_name|
|-------|----------|---------|
orders
|----------------------|
|order_id|user_id|total|
|--------|-------|-----|
Now with the function discussed above it would be easy to generate a table for all the users or orders but what I would like to do is have a function where I could dynamically join tables and for example list all users and the number of orders they've made or list all orders from user x. I know that this would be possible with many different functions but I'm really interested in developing a way of doing this dynamically and basically building all the relationships somehow in the program and then be able to call one function and request columns x,y and z
My thinking so far would be (again for this example) somehow define that number of orders for user i = count(order_id) where user_id = i
Hope this makes sense and thank you in advance
The INFORMATION_SCHEMA.KEY_COLUMN_USAGE table can be used to find all foreign key relationships from a particular table to other tables, e.g:
SELECT `TABLE_NAME`,
`COLUMN_NAME`,
`REFERENCED_TABLE_NAME`,
`REFERENCED_COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`
WHERE `TABLE_SCHEMA` = SCHEMA() -- current schema
AND `REFERENCED_TABLE_NAME` IS NOT NULL
AND `TABLE_NAME` = 'orders'; -- name of table to get relationships to other tables
This should return something like the following:
+--------------+-------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+--------------+-------------+-----------------------+------------------------+
| orders | user_id | users | user_id |
+--------------+-------------+-----------------------+------------------------+
The above can be done in PHP and the results can then be iterated over to dyamically construct a query that selects from those tables, joining on the listed columns. Will leave that part as an exercise ;-)
You wouldn't need to make a function to grab data from first table then loop around them and get data from the second table.
SQL can do this for you with 1 hit on the database.
All what you need to do is join the two tables, and grab the data you want..
If I understood what you need right, you want to grab all users id from the first table, and get their order count from the second table.
A simple join or selecting from both table could do that, and I suggest something like:
Select a.user_id, b.count(order_id)
FROM table1 as a, table2 as b
WHERE a.user_id = b.user_id
Group By a.user_id
Or you could join the tables and do a similar task.
I am assuming you're gonna access database from PHP code, so try that, and give me back your feedback.
This is easy to implement but we have to fix few things.
Our requirement:
1. Identify Tables according to column name.
2. How we can Join those tables.
3. How to resolve ambiguity of columns.
Solution:
Unique column name for each field or no table has duplicate column name.
To achieve it we should have fix table prefix for each table.
for example:
your column name could be odr_orderid and usr_orderid.
Now by identifying unique prefixes, we can identify tables.
Now issue arises how to join these tables
To resolve it:
Create an another table strong JOIN keys and JOin type Left, right,inner or full.
Thats all Now you can make the query as you want.
I am trying to make a notification list that displays notifications from multiple different content types and there respective database tables.for each content type There is a subscribe table with the respective subscriptions which I need to retrieve.the tables and there respective subscriptions tables are as follows
--------------------------
content type | subscriptions
-------------+------------
group | subscribegroup
-------------+------------
discussion | subscribediscussion
-------------+------------
forum | subscribeforum
-------------+------------
thread | subscribethread
-------------+------------
The problem I have is that each content subscription table has a different name for the id of its values eg
This is how I would get the data from one content a single table with its respective subscription table and then use UNION but isnt union heavy on the database server??
SELECT *
FROM thread t
JOIN subscribethread s ON (t.threadid = s.threadid)
WHERE userid= $currentuserid
How would I join multiple instances of other content types above with this? Thanks
We use JOIN when we need combine columns from few tables INTO ONE(or more) row. As i understand you need combine ROWS FROM DIFFERENT TABLES in one result table. There is no UNION alternative with such schemas structure.
I have 3 tables, something like this (only posting relevant info):
USER:
-----
user_id
POST:
----
post_id
user_id
IMAGE:
----
image_id
post_id
What I am trying to do, is allow a user to search for posts, they can choose whether or not the post results include images or not.
So it'll be something like:
if ($images_selected) { $SQL_TO_FIND_POSTS_WITH_IMAGES; } else { $SQL_TO_FIND_POSTS_WITHOUT_IMAGES; }
Having a lot of trouble getting my head round how I will do this.
Cannot change any table structure as it must be this way.
This should get your started
select * from
post pp
join user uu on p.user_id=uu.user_id
left join image mg on mg.post_id=pp.post_id
The above gives me all posts regardless of image or not
-- To exclude images, add the following
where mg.post_id is null
Query without table aliases
select * from
post
join user on post.user_id=user.user_id
left join image on image.post_id=post.post_id
I have a table called Products that contains Titles of products. Some of these Titles have words I would like to replace. The table contains over 6,000 records. The text strings are found in the Title Column
ID | Title | Description | Price
I have another table called ReplaceText that contains a list of strings I am searching for and new text string. (e.g. small | tiny) This currently has 102 records.
ID | OldString | NewString
I would like to create a PHP/MySQL script to search the Title field in the Products table for matching words from the 'OldStringfield in theReplaceText` table.
I have tried various methods but all can't crack the code. Please help :)
Thank you in advance.
I suggest the following approach, using only SQL queries.
First, create a temporary table ProductsTMP containing only the rows Products with a new Title.
CREATE TEMPORARY TABLE ProductsTMP AS
SELECT p.ID, r.NewString AS Title, p.Description, p.Price
FROM Products p INNER JOIN ReplaceText r ON p.Title = r.OldString;
Then, remove the old rows from the original Products table:
DELETE FROM Products
WHERE ID IN (SELECT ID FROM ProductsTMP);
Finally, add the updated rows from ProductsTMP to the original table Products, and remove the temporary table:
INSERT INTO Products (ID, Title, Description, Price)
SELECT ID, Title, Description, Price FROM ProductsTMP;
DROP TABLE ProductsTMP;
I have two tables images2 and image_data
So the goal is to have 1 table for ALL the image uploads (images2) and then the image_data is to assign that image with different options.
So for example, here is some sample data:
So image_id 10 has more than one row, because this image is associated with both TN and CQ. And they could also be associated with more than one language and slide, so I would add on to the second row and change slide_id or language_id .. if wanted to add more, than I would add a new row for it.
The goal is to have a list of all the images, and then when you click on it it pops up and you can edit the options and change it straight from there.
I need help writing a query. The one I have right now:
SELECT images2.id, images2.filename, image_data.slide_id, image_data.language_id,
image_data.type FROM images2
LEFT JOIN image_data ON images2.id = image_data.image_id
A couple things wrong with that query.. It is showing the duplicates, because image_id 10 has two rows.
But I need that second row of image #10 because I need to see that it is also associated with CQ so I can check the checkbox when it pops up.
So I need to create a query to show ALL the unique images no duplicates, with all of the options it has.
I'm not sure the best way to do this.. do I need to re-do the way my database tables are? Any help is appreciated.
Thanks.
What you could do is use GROUP_CONCAT() to turn values in multiple rows into a single concatenated string. The following retrieves the ids of slides and languages as well as their names to better facilitate your form.
SELECT
a.id,
a.filename,
GROUP_CONCAT(CONCAT(b.slide_id, '::', c.slide_name)) AS slides,
GROUP_CONCAT(CONCAT(b.language_id, '::', d.language_name)) AS languages,
GROUP_CONCAT(b.type) AS types,
FROM
images a
LEFT JOIN
image_data b ON a.id = b.image_id
LEFT JOIN
slides c ON b.slide_id = c.id
LEFT JOIN
languages d ON c.language_id = d.id
GROUP BY
a.id
Your result set for image 10 will look something like:
id | image_filename | slides | languages | types
-------------------------------------------------------------------------
10 | p170sfhe... | 5::slide5 | 1::language1 | TN,CQ
In php, just explode() the strings based on the delimiters.
you could use GROUP_CONCAT to get a csv of the fields:
SELECT
images2.id,
images2.filename,
GROUP_CONCAT(DISTINCT image_data.slide_id) AS slides,
GROUP_CONCAT(DISTINCT image_data.language_id) AS langs,
GROUP_CONCAT(DISTINCT image_data.type) AS types
FROM images2
LEFT JOIN image_data ON (images2.id = image_data.image_id)
GROUP BY images2.id