Difficulty with join 3 tables in a query in php - php

My database has 3 tables i wish to access in the select query but I cannot seem to get it to work. Selecting from 2 tables works fine so I know everything else is working apart from my code for selecting from 3 tables. My database has been created on PHPmyadmin
The Tables are as follows:
forum_replies
reply_id
topic_id
user_id
reply_text
reply date
forum_topics
topic_id
category_id
user_id
topic_title
topic_description
topic_date
users
user_id
username
This is the code I have tried to use and shows the fields I wish to select:
$queryreply = "SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username
forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date
FROM forum_replies
JOIN forum_topics
ON forum_replies.topic_id = forum_topics.topic_id
JOIN users
ON forum_replies.user_id = users.user_id
";
$result = mysql_query($queryreply) or die (mysql_error());
$row = mysql_fetch_array($result);
Example in code would be appreciated. Thanks

Use this query:
SELECT a.reply_text, a.reply_date, b.topic_title, c.username
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed
Apart from syntax errors, you should use LEFT JOIN and table alias in your case.
To show also the topic creator's username, you can adjust the query to the following:
SELECT a.reply_text, a.reply_date, b.topic_title, c.username AS reply_user, (SELECT username FROM users WHERE user_id=b.user_id) AS topic_creator
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed

You miss the , after users.username..
SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username,
forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date

Related

Get the last records from 3 tables

My tables
$sql="SELECT *
FROM addresses
LEFT JOIN users ON address_id = user_id
LEFT JOIN notes ON note_id = user_id
ORDER BY id DESC
LIMIT 1";
This is my SQL query, my task is to show the last records from 3 tables, but the table is blank, I don't know why,thanks in advance people :)
I guess the problem is coming from the ORDER BY id DESC .
Indeed, you have no column so called id.
You should probably remove this clause, in order to make your code work.
If you want to take the last records anyway, you can put an ORDER BY address_id DESC which will do the job !
The code directly edited :
$sql="SELECT *
FROM addresses
LEFT JOIN users ON address_id = user_id
LEFT JOIN notes ON note_id = user_id
ORDER BY adress_id DESC
LIMIT 1";
This may work:
SELECT a.address_id, u.user_id, n.note_id
FROM addresses a
LEFT JOIN users_addresses ua ON ua.ua_address_id = a.address_id
LEFT JOIN users u ON u.user_id = ua.ua_user_id
LEFT JOIN notes n ON n.note_user_id = u.user_id
ORDER BY a.address_id DESC
LIMIT 1
Here is the query to get all data from all the tables, not sure what do you mean last records from 3 tables, I can see four tables there:
SELECT *
FROM `addresses`
LEFT JOIN `users_addresses` ON `users_addresses`.`ua_address_id` = `addresses`.`address_id`
LEFT JOIN `users` ON `users`.`user_id` = `users_addresses`.`ua_user_id`
LEFT JOIN `notes` ON `notes`.`note_user_id` = `users`.`user_id`;

How to join three MySQL tables with unrelated data?

So I have a webpage that shows an image and information about it, and I also have three tables.
IMAGES USERS COMMENTS
id user_id id
user_id username user_id
username password comment
title isadmin date
image (location) points
description signup_date
points email
category city
bio
profile_image
I need to use all the information from the images and comments table. But I also need to retrieve the profile_image of the user that posted the comment and image. I cannot figure out how to do this: here is what I have so far.
$conn = new PDO ("mysql:host=localhost;dbname=project", "root", "pass");
$stmt = $conn->prepare("
SELECT images.*, users.profile_image, comments.*
FROM (images.id JOIN comments ON images.id = comments.id)
LEFT JOIN users
ON images.user_id = user.profile_image
");
Am I close? or trying the impossible here!?
it's a lot simpler then you'd think :)
the tables are NOT unrelated, they all have the same key - user_id and that's how you join them.
your query should look like this:
SELECT images.*, users.profile_image, comments.*
FROM images
JOIN users ON images.user_id = users.user_id
JOIN comments ON comments.user_id = users.user_id AND images.id = comments.id
this is assuming the images.id and comments.id match (I suspect they do not - but you did not give us enough info)
looking at your table structure, comments and images appear to have no connection, so maybe query them separately to avoid duplicated & confusing data
---UPDATE---
assuming you've added image_id to comments this is your query:
SELECT images.*, users.profile_image, comments.*
FROM images
LEFT JOIN users ON images.user_id = users.user_id
LEFT JOIN comments ON comments.user_id = users.user_id AND images.id = comments.image_id
what LEFT JOIN does is return 'images' that don't necessarily have 'users' or 'comments' connected to them.
I guess this will do the trick:
SELECT i.*, u.profile_image, c.*
FROM images i
LEFT JOIN comments c ON i.user_id = c.user_id
LEFT JOIN users u ON i.user_id = u.user_id
I think it's:
> SELECT images.*, users.profile_image, comments.*
> FROM images
> INNER JOIN users ON images.user_id= users.user_id
> INNER JOIN comments ON users.user_id= comments.user_id

MySQL Using SUM with multiple joins

I have a projects table and a tasks table I want to do a query that gets all projects and the sum of the time_spent columns grouped by project id. So essentially list all projects and get the total of all the time_spent columns in the tasks table belonging to that project.
With the query posted below I get the latest added time_spent column and not the sum of all the columns.. :S
Below is the query I have at the moment:
SELECT `projects`.`id`, `projects`.`description`, `projects`.`created`,
`users`.`title`, `users`.`firstname`, `users`.`lastname`, `users2`.`title`
as assignee_title, `users2`.`firstname` as assignee_firstname,
`users2`.`lastname` as assignee_lastname,
(select sum(tasks2.time_spent)
from tasks tasks2
where tasks2.id = tasks.id)
as project_duration
FROM (`projects`)
LEFT JOIN `users`
ON `users`.`id` = `projects`.`user_id`
LEFT JOIN `users` as users2
ON `users2`.`id` = `projects`.`assignee_id`
LEFT JOIN `tasks` ON `tasks`.`project_id` = `projects`.`id`
GROUP BY `projects`.`id`
ORDER BY `projects`.`created` DESC
Below is my projects table:
Below is my tasks table:
Thanks in advance!
Usually this query will help you.
SELECT p.*, (SELECT SUM(t.time_spent) FROM tasks as t WHERE t.project_id = p.id) as project_fulltime FROM projects as p
In your question, you don't say about users. Do you need users?
You are on right way, maybe your JOINs can't fetch all data.
This query should do it for you.
Note, whenever you do a group by you must include every column that you select from or order by. Some MySql installations don't prevent you from doing this, but in the end it results in an incorrect result set.
As well you should never do a query as part of your SELECT statement, known as a sub-query, as it will result in an equal amount of additional queries in relation to the number of rows returned. So if you got 1,000 rows back, it would result in 1,001 queries instead of 1 query.
SELECT
p.id,
p.description,
p.created,
u.title,
u.firstname,
u.lastname,
a.title assignee_title,
a.firstname assignee_firstname,
a.lastname assignee_lastname,
SUM(t.time_spent) project_duration
FROM
projects p
LEFT JOIN
users u ON
u.id = p.user_id
LEFT JOIN
users a ON
a.id = u.assignee_id
LEFT JOIN
tasks t ON
t.project_id = p.id
GROUP BY
p.id,
p.description,
p.created,
u.title,
u.firstname,
u.lastname,
a.title,
a.firstname,
a.lastname
ORDER BY
p.created DESC

MySql : left join users table with transactions table return several rows

I have 2 tables : users and paypal_transactions
For each user, we have an id (named user_id in paypal_transactions table)
A user may have several paypal_transactions. Relation one to many
I need to grab the latest transaction id (ordered by date_dt DESC) when I do my query
My current query :
SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction` ON (`User`.`id` = `Transaction`.`user_id`)
ORDER BY `User`.`id` DESC
LIMIT 500
Currently with one transaction per user, it works fine. BTW with many transactions I still get the 1st entry from paypal_transactions table (the oldest, but I want the latest from now).
I did many tries, without success.
Thanks for your help !
Here you go:
SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN (SELECT user_id, MAX(date_dt) AS max_date
FROM `pronostics_framework`.paypal_transactions
GROUP BY user_id) AS max_trans
ON User.id = max_trans.user_id
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction`
ON (max_trans.user_id = `Transaction`.`user_id` AND max_trans.max_date = Transation.date_dt)
ORDER BY `User`.`id` DESC
LIMIT 500
Another way, based on the first query in the first answer at Retrieving the last record in each group:
SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction` ON Transaction.user_id = User.id
LEFT JOIN `pronostics_framework`.paypal_transactions AS Transactions1
ON Transactions1.user_id = Transactions.user_id AND Transactions1.user_id > Transactions.user_id
WHERE Transactions1.user_id IS NULL
ORDER BY `User`.`id` DESC
LIMIT 500

Problem with SQL statement in MySQL

I am running an SQL statement:
$sql = "SELECT pic, userid
FROM user_details
INNER JOIN wp_users ON user_details.userid
WHERE wp_users.id = user_details.userid
LIMIT $recordstart, $pagesize
";
The query is meant to select records from user_details and wp_users, but should only select if there is a match (wp_users.id = user_details.userid).
The target is for it to basically select from a table while retrieving a record (based on the id match) from the other table
The problem is that it shows duplicate records. How can I fix this problem?
You should put your JOIN condition after ON. Like this:
$sql="select pic, userid
from user_details
inner join wp_users on (wp_users.id=user_details.userid)
limit $recordstart, $pagesize";
But the real problem is that you have more then 1 record in user_details for each corresponding record in wp_users (or vise versa).
INNER JOIN is causing database to make a Cartesian product of user_details and wp_users records. Then result table is filtered by your current WHERE condition (wp_users.id=user_details.userid). Depends on your needs you can use GROUP BY or DISTINCT if you want to retrieve unique records only.
For example, if you need userid to be unique:
$sql="select pic, userid
from user_details
inner join wp_users on (wp_users.id=user_details.userid)
group by userid
limit $recordstart, $pagesize";
SELECT DISTINCT pic, userid
FROM user_details
INNER JOIN wp_users ON wp_users.id=user_details.userid
LIMIT $recordstart, $pagesize
Use DISTINCT to return only unique rows and complete your join condition in the ON section:
$sql="select distinct pic, userid
from user_details
inner join wp_users on wp_users.id=user_details.userid
limit $recordstart, $pagesize";
use GROUP BY , because it shows duplicate records if there is multiple records in second table per on one record in first table
You left out the = part of the ON by accident.
$sql="select pic, userid
from user_details
inner join wp_users on user_details.userid
= wp_users.id
where wp_users.id=user_details.userid
limit $recordstart, $pagesize";
I might try
$sql = "select pic, userid
from user_details
inner join wp_users on user_details.userid = wp_users.id
limit $recordstart, $pagesize";

Categories