Use Sql Join two times on a single table - mysql

This is my query in 3 Nested form. What i want is to re-write this query using JOINS but the problem is same table is repeating two times as you can see.
$query = "
SELECT
*
FROM userinfo
WHERE id IN (
SELECT DISTINCT
iduser
FROM u_n_relation
WHERE idnetwork IN (
SELECT
idnetwork
FROM u_n_relation
WHERE iduser = '$userid'
)
)
AND virtual_name LIKE CONCAT('%', ?, '%')
ORDER BY id LIMIT 5
"
What i tried was this :
$query = "
SELECT
userinfo.*
FROM userinfo
INNER JOIN u_n_relation ON (u_n_relation.iduser = userinfo.id)
WHERE
(userinfo.virtual_name LIKE CONCAT('%', ?, '%')
AND u_n_relation.iduser = '$iduser')
ORDER BY userinfo.id LIMIT 5
"
But still not getting the correct result.
Can anyone please shed some light on how to do this?
Basically what the query says is :
Fetch the details of the users who have joined the networks you have joined.

select distinct is not needed when you use in. However, it may be needed when you use join. Otherwise you can turn the ins into inner joins:
SELECT ui.*
FROM userinfo ui JOIN
(SELECT DISTINCT unr.iduser
FROM u_n_relation unr JOIN
u_n_relation unr2
ON unr.idnetwork = unr2.idnetwork and
unr2.iduser = '$userid'
WHERE unr.virtual_name LIKE CONCAT('%', ?, '%')
) unr
ON ui.id = unr.iduser
ORDER BY id
LIMIT 5;

Firstly, Mark L. is correct in that aliases are the key to JOINing the same table multiple times in a query.
Secondly, holy crap formatting. Formatting is especially important when posting your query to ask a question about it. Your formatting caused Gordon L. to mis-read which table the "virtual_name" field was in.
Initially your first query didn't make sense to me but jackkorbins comment got me to view it again and I get it this time - here it is formatted more read-ably:
SELECT *
FROM
userinfo
WHERE
id IN (-- This sub-query returns *any* iduser that is a member
-- of those same networks
SELECT DISTINCT
iduser
FROM
u_n_relation
WHERE
idnetwork IN (-- This sub-query returns the multiple networks
-- that have $userid as a member
SELECT
idnetwork
FROM
u_n_relation
WHERE
iduser = '$userid'))
AND virtual_name LIKE CONCAT('%', ?, '%')
ORDER BY
id
LIMIT 5
So another way to make a JOIN version of that query would look like:
SELECT DISTINCT
ui.*
FROM
u_n_relation unr
INNER JOIN u_n_relation net
ON (net.idnetwork=unr.idnetwork)
INNER JOIN userinfo ui
on ( ui.id = net.iduser )
WHERE
unr.iduser = '$iduser'
and ui.virtual_name LIKE CONCAT('%', ?, '%')
ORDER BY
ui.id
LIMIT 5
Sorry for my earlier confusion. :-)

Related

Left join sql query

I want to get all the data from the users table & the last record associated with him from my connection_history table , it's working only when i don't add at the end of my query
ORDER BY contributions DESC
( When i add it , i have only the record wich come from users and not the last connection_history record)
My question is : how i can get the entires data ordered by contributions DESC
SELECT * FROM users LEFT JOIN connections_history ch ON users.id = ch.guid
AND EXISTS (SELECT 1
FROM connections_history ch1
WHERE ch.guid = ch1.guid
HAVING Max(ch1.date) = ch.date)
The order by should not affect the results that are returned. It only changes the ordering. You are probably getting what you want, just in an unexpected order. For instance, your query interface might be returning a fixed number of rows. Changing the order of the rows could make it look like the result set is different.
I will say that I find = to be more intuitive than EXISTS for this purpose:
SELECT *
FROM users u LEFT JOIN
connections_history ch
ON u.id = ch.guid AND
ch.date = (SELECT Max(ch1.date)
FROM connections_history ch1
WHERE ch.guid = ch1.guid
)
ORDER BY contributions DESC;
The reason is that the = is directly in the ON clause, so it is clear what the relationship between the tables is.
For your casual consideration, a different formatting of the original code. Note in particular the indented AND suggests the clause is part of the LEFT JOIN, which it is.
SELECT * FROM users
LEFT JOIN connections_history ch ON
users.id = ch.guid
AND EXISTS (SELECT 1
FROM connections_history ch1
WHERE ch.guid = ch1.guid
HAVING Max(ch1.date) = ch.date
)
We can use nested queries to first check for max_date for a given user and pass the list of guid to the nested query assuming all the users has at least one record in the connection history table otherwise you could use Left Join instead.
select B.*,X.* from users B JOIN (
select A.* from connection_history A
where A.guid = B.guid and A.date = (
select max(date) from connection_history where guid = B.guid) )X on
X.guid = B.guid
order by B.contributions DESC;

SQL query that limits the results to one when using count inside count

I am trying to select the count of likes on a specific project. The idea i came up with is
CAST(count(uploads.ID in (SELECT uploadID from votes)) as decimal) as numberoflikes
this works but the query then only returns one thing.
Entire query
SELECT DISTINCT users.NAME AS username
,users.ID AS userID
,subjects.NAME AS subjectname
,uploads.TIME
,uploads.description
,uploads.NAME
,uploads.ID
,CASE
WHEN uploads.ID IN (
SELECT uploadID
FROM votes
WHERE userID = 2
)
THEN CAST(1 AS DECIMAL)
ELSE CAST(0 AS DECIMAL)
END AS liked
,CASE
WHEN uploads.ID IN (
SELECT uploadID
FROM bookmarks
WHERE userID = 2
)
THEN CAST(1 AS DECIMAL)
ELSE CAST(0 AS DECIMAL)
END AS bookmarked
,CAST(count(uploads.ID IN (
SELECT uploadID
FROM votes
)) AS DECIMAL) AS numberoflikes
FROM uploads
INNER JOIN subjects ON (subjects.ID = uploads.subjectID)
INNER JOIN users ON (users.ID = uploads.userID)
INNER JOIN uploadGrades ON (uploads.ID = uploadGrades.uploadID)
INNER JOIN grades ON (grades.ID = uploadGrades.gradeID)
WHERE uploads.active = 1
AND subjects.ID IN (
SELECT subjectID
FROM userSubjects
INNER JOIN users ON (users.ID = userSubjects.userID)
WHERE userSubjects.userID = 2
)
AND grades.ID IN (
SELECT userGrades.gradeID
FROM uploadGrades
INNER JOIN userGrades ON (uploadGrades.gradeID = userGrades.gradeID)
WHERE userGrades.userID = 2
)
ORDER BY uploads.trueRating DESC;
Lets try a reduce version of your query, That is the base to get better answers
I reduce the initial query to user and upload to start. Also remove the fields you already know how to calculate.
.
SELECT DISTINCT users.NAME AS username
,users.ID AS userID
,uploads.NAME
,uploads.ID
,CAST(count(uploads.ID IN (
SELECT uploadID
FROM votes
)) AS DECIMAL) AS numberoflikes
FROM uploads
INNER JOIN users ON (users.ID = uploads.userID)
WHERE uploads.active = 1
ORDER BY uploads.trueRating DESC;
Then add votes with LEFT JOIN to replace the SELECT in the COUNT that way if not match you will get NULL and as I say in my comment COUNT doesnt count NULL's
.
SELECT DISTINCT users.NAME AS username
,users.ID AS userID
,uploads.NAME
,uploads.ID
,CAST(count(votes.uploadID)) AS DECIMAL) AS numberoflikes
FROM uploads
INNER JOIN users ON (users.ID = uploads.userID)
LEFT JOIN votes ON (uploads.ID = votes.uploadID)
WHERE uploads.active = 1
ORDER BY uploads.trueRating DESC;
Try something like this...
SELECT users.name as username, users.ID as userID, subjects.name as subjectname,
uploads.time, uploads.description, uploads.name, uploads.ID,
count(userVotes.userId), count(bookmarksMade.userId),
FROM uploads
join subjects on(subjects.ID = uploads.subjectID)
join users on(users.ID = uploads.userID)
join uploadGrades on(uploads.ID = uploadGrades.uploadID)
join grades on(grades.ID = uploadGrades.gradeID)
left join (select userId, uploadId from votes where userId = 2) as userVotes on uploads.id = userVotes.uploadId
left join (select userId, uploadId from bookmarks where userId = 2) as bookmarksMade on uploads.id = bookmarksMade.uploadId
join userSubjects on subjects.id = userSubjects.subjectID
WHERE uploads.active = 1 AND
userSubjects.userID = 2
ORDER BY uploads.trueRating DESC;
But, I am leaving out the userGrades thing, because you are doing a funky join there that I don't really understand (joining two tables on something that looks like it is not the whole primary key on either table).
Anyway, you really need to go to something more like this or what Oropeza suggests in his answer. Get more direct about what you want. This query looks like a monster that has been growing and getting things added in with "IN" clauses, as you needed them. Time to go back to the drawing board and think about what you want and how to get at it directly.
count(uploads.ID in (SELECT uploadID from votes)) as numberoflikes
group by uploads.Id ORDER BY uploads.trueRating DESC
I managed to do it like this. If i added the group by then it split the numberoflikes into rows and returned more then one row. Thanks for the help!

LEFT JOIN SUM with WHERE clause

The following query always outputs SUM for all rows instead of per userid. Not sure where else to look. Please help.
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
) assignments ON (userid = assignments.userid AND ticketid = ?)
WHERE ticketid = ?
ORDER BY assigned,scheduled
If you want to keep the SELECT *, you would have to add a group by clause in the subquery. Something like this
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
GROUP BY userid
) time_entriesSummed ON time_entriesSummed.userid = assignments.userid
WHERE ticketid = ?
ORDER BY assigned,scheduled
But a better way would be to change the SELECT * to instead select the fields you want a add a group by clause directly. Something like this
SELECT
assignments.id,
assignments.assigned,
assignments.scheduled,
SUM(time_entries.timeworked) AS totalTimeworked
FROM assignments
LEFT JOIN time_entries
ON time_entries.userid = assignments.userid
GROUP BY assignments.id, assignments.assigned, assignments.scheduled
Edit 1
Included table names in query 2 as mentioned in chameera's comment below

mysql like and different value not working

I'm doing a form of research every things work fine except the clause <> i don't know why happen. any help?
this is my query
SELECT users . * , image_upload.name_image
FROM users
LEFT JOIN image_upload ON users.profile_image = image_upload.id_image
WHERE users.id <>1
AND LOWER( users.name ) LIKE 'f%'
OR LOWER( users.surname ) LIKE 'f%'
LIMIT 5
when start the query, it shows the row with the id = 1 logically is not correct.
Try this:
SELECT users . * , image_upload.name_image
FROM users
LEFT JOIN image_upload ON users.profile_image = image_upload.id_image
WHERE users.id <>1
AND (LOWER( users.name ) LIKE 'f%'
OR LOWER( users.surname ) LIKE 'f%')
LIMIT 5
Remember that the OR statement really has to be in parenthesis due to the way that operators are processed.
Here's a link for you:
http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

Join two strings from db together

I have produced the following query.
SELECT t.id AS playerid,
dp.first_name,
dp.surname
FROM ".TBL_FOOT_CAREER_TEAMS." t
INNER JOIN ".TBL_FOOT_CAREER_DB_PLAYERS." dp
ON dp.id = t.playerid
WHERE t.careerid = '$career'
AND (dp.first_name LIKE '%{$keyword[$i]}%')
OR (dp.surname LIKE '%{$keyword[$i]}%')
OR (`dp.first_name + dp.surname` LIKE '%{$keyword[$i]}%')
There are two columns in the database. first_name and surname. As you can see, I'm trying to check if the keyword is in either of those columns. I also try and make them into one complete name and check if that's what the search term is aswell.
I'm getting an error so I can assume this isn't the way to do it!!
Can someone help :)
Thanks
SELECT t.id AS playerid,
dp.first_name,
dp.surname
FROM ".TBL_FOOT_CAREER_TEAMS." t
INNER JOIN ".TBL_FOOT_CAREER_DB_PLAYERS." dp
ON dp.id = t.playerid
WHERE (t.careerid = '$career') AND
(
(dp.first_name LIKE concat('%', $keyword[$i], '%')) OR
(dp.surname LIKE concat('%', $keyword[$i], '%')) OR
(CONCAT(dp.first_name, ' ',dp.surname) LIKE concat('%', $keyword[$i], '%'))
)
UPDATE
since you are concactenating the name, you can it like this:
SELECT t.id AS playerid,
dp.first_name,
dp.surname
FROM ".TBL_FOOT_CAREER_TEAMS." t
INNER JOIN ".TBL_FOOT_CAREER_DB_PLAYERS." dp
ON dp.id = t.playerid
WHERE (t.careerid = '$career') AND
(
CONCAT(dp.first_name, ' ',dp.surname) LIKE concat('%', $keyword[$i], '%')
)
Use CONCAT() in your query: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
...
OR CONCAT(dp.first_name, dp.surname) LIKE '%{$keyword[$i]}%'