SQL Query INNER JOIN - unexpected results - php

I have tables:
trips: Trip_Num, Trip_Type,Trip_Geographic, etc.
travelers_trips_history: Username, Trip_Num, Trip_Type, Trip_Season, etc.
In table 2 there are trips the user did and I need to know what is the most common Trip_Geographic that in his trip's history (The Trip_Geographic need to be known by table 1 - trips by his Trip_Num).
I am doing a project in PHP and need to do a SQL query for a specific user (by his username) - need to receive a table that the columns are: 1. Trip_Geographic, count of the occurrence the Trip_Geographic is in the travelers_trips_history.
Attached the tables I have:
trips
travelers_trips_history
The query I did:
$query = "select traveler_trips_history.*, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
GROUP BY Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC
WHERE traveler_trips_history.Traveler_Username = $username";
I receive a error about the Group BY (check syntax), however, I am not sure the query is going to do what it should do.

Try this
SELECT traveler_trips_history.*
,COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history
INNER JOIN trips ON travelers_trips_history.Trip_Num = trips.Trip_Num
WHERE traveler_trips_history.Traveler_Username = $USERNAME
GROUP BY traveler_trips_history.travelers_trips_history
,traveler_trips_history.Username
,traveler_trips_history.Trip_Num
,traveler_trips_history.Trip_Type
,traveler_trips_history.Trip_Season
ORDER BY Trip_Geographic_occurrence DESC

You have 2 issues in your query:
1- You should have the where clause before the GroupBy Clause
2- If you GroupBy Col1, you can only select Col1 or use Aggregate Functions on another Columns (SUM, AVG, etc...)
You need to check the Rules for GroupBy and understand it better.
Edit after your comment:
$query = "select Trip_Geographic, COUNT(*) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
WHERE traveler_trips_history.Traveler_Username = $username
GROUP BY Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC";

Try like this
The problem is your where clause and group by columns.
SELECT tr.Trip_Geographic
,COUNT(hs.*) AS Trip_Geographic_occurrence
FROM traveler_trips_history hs
INNER JOIN trips tr ON hs.Trip_Num = tr.Trip_Num
WHERE hs.Username = $USERNAME
GROUP BY tr.Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC

Your problem is Haing WHERE clause after GROUP By and using columns that are not in GROUPED BY or AGGREGATE functions.
Try the following which has the username, trip_geographic and the no of trips.
select traveler_trips_history.Traveler_Username, traveler_trips_history.Trip_Geographic, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
GROUP BY Trip_Geographic, traveler_trips_history.Traveler_Username
having traveler_trips_history.Traveler_Username = $username
ORDER BY Trip_Geographic_occurrence DESC

Related

Count for two column from a table using groupby or unionall based on users

I want count for two columns from a single query which are in same table.
1- followerscount
2- followeecount
I am using union and groupby to get count for two columns but only able to get only one column count from query.
Query I used below:
SELECT follow_attr.username, follow_attr.followerid, follow_attr.followeeid, follow_attr.followercount, follow_attr.followeecount
FROM (
SELECT u.username, dff.followerid AS followerid, dff.followeeid AS followeeid, count(dff.followerid) AS followercount, count(dff.followeeid) AS followeecount
FROM tablename AS dff
LEFT JOIN user AS u ON u.userid = dff.followerid
GROUP BY dff.followerid
UNION ALL
SELECT u.username, dffs.followerid AS followerid, dffs.followeeid AS followeeid, count(dffs.followerid) AS followercount, count(dffs.followeeid) AS followeecount
FROM tablename AS dffs
LEFT JOIN user AS u ON u.userid = dffs.followeeid
GROUP BY dffs.followeeid
) AS follow_attr
WHERE follow_attr.username IS NOT NULL
GROUP BY follow_attr.followerid, follow_attr.followeeid
ORDER BY RAND()
LIMIT 0,6
I am not been able to get followeecount in this query.
Let me know whats wrong in that procedure.
Do this
SELECT COUNT(followercount) AS f_count, COUNT(followeecount) AS fe_count FROM tablename

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`;

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

getting data from four tables with tight WHERE clause

i need help getting data from different tables and insert into other different table Here are the Queries
"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"
"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
// $parentID need to be matched from above query parentID,
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query
"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query
Last 2 queries are from same table but using different where clause
i used different inner join left join from solutions posted here but non of these worked for me stuck since last 2 weeks please help
PS data from all above Queries will be inserted to a single table i need these to be combined so i can have them all in one place
If you want to perform the operation in same query use 'OR'
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID OR aBUserID = $topicaBUserID";
Please try this
SELECT userName from users where aBUserID IN(SELECT aBUserID FROM comments WHERE status = 'APPROVED')
Couldn't test it but Maybe this is what you are looking for.
SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID,
t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
u.userName
FROM
comments c
left outer join topic t on t.topicID = c.parentID
left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
c.status = 'APPROVED' and t.status = 'APPROVED';
try this:
SELECT
comment.[commentID],
comment.[date],
comment.[comment],
comment.[subject],
comment.[parentID],
comment.[aBUserID],
commentuser.[userName],
topic.[topicID],
topic.[subForumID],
topic.[aBUserID],
topic.[lastPostID],
topic.[views],
topic.[replies],
topic.[startDate],
topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
SELECT
t.[topicID],
t.[subForumID],
t.[aBUserID],
t.[lastPostID],
t.[views],
t.[replies],
t.[startDate],
u2.[userName] --user from users table joined to topics table
FROM topic t
LEFT OUTER JOIN users u
ON u.aBUserID = t.[aBUserID]
WHERE t.[status] = 'APPROVED'
) topic
ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'

expanding a mysql JOIN query in PHP

I need to alter my existing JOIN query below to also include the data from users.image correlating to the UserID of the post maker. Something like:
users.image WHERE users.UserID = posts.userid
I am not very good with join queries yet. How would I do this?
Existing Query:
$result = mysql_query("SELECT posts.* FROM listen JOIN posts ON posts.userid = listen.listenid WHERE listen.userid = '$user_id' ORDER BY DATE desc") or die(mysql_error());
Just add another JOIN clause:
SELECT posts.*
FROM listen
JOIN posts ON (posts.userid = listen.listenid)
JOIN users ON (users.UserID = posts.userid)
WHERE listen.userid = '$user_id'
ORDER BY DATE desc
You may need to change the JOIN to a specific join such as LEFT JOIN, depending on what you're after.
Btw, it is easier to see the query on multiple lines.
Edit: You'll probably want to add additional items that you are selecting with your fields, such as SELECT posts.*, users.*

Categories