Add additional joins to already joined table in SQL - mysql

I have a existing query where I am using joins (thanks RADAR) to get my data.
Working SQL
SELECT
IFNULL(f.field_full_name_value, 'No Value'), u.name, u.uid, n.title, n.nid, a.timestamp, d.field_video_duration_value AS duration
FROM
db_node_view_count a
join db_node n
ON a.nid = n.nid
JOIN db_field_data_field_video_duration d
ON n.nid = d.entity_id
JOIN db_users u
ON a.uid = u.uid
AND u.uid <> 1
LEFT JOIN db_field_data_field_full_name f
ON u.uid = f.entity_id
ORDER BY u.uid desc
What I want to do is that I want to extend the query to show roles of a db_users u. There is a table called db_roles, which contain all role names with a primary key rid. Then the second table is db_users_roles, which contains a matching uid (from db_users u) and rid to show which user selected which role.
So what I did was that under ON a.uid = u.uid, I added JOIN db_users_roles ur ON u.uid = ur.uid JOIN db_role r ON ur.rid = r.rid. It works fine but it shows duplicate rows. Any idea why it's happening?
SELECT
IFNULL(f.field_full_name_value, 'No Value'), r.name, u.name, u.uid, n.title, n.nid, a.timestamp, d.field_video_duration_value AS duration
FROM
db_node_view_count a
join db_node n
ON a.nid = n.nid
JOIN db_field_data_field_video_duration d
ON n.nid = d.entity_id
JOIN db_users u
ON a.uid = u.uid
LEFT JOIN db_users_roles ur
ON u.uid = ur.uid
LEFT JOIN db_role r
ON ur.rid = r.rid
AND u.uid <> 1
LEFT JOIN db_field_data_field_full_name f
ON u.uid = f.entity_id
ORDER BY u.uid desc
UPDATE
With help from Joe, here is a slight update:
SELECT
IFNULL(f.field_full_name_value, 'No Value'), GROUP_CONCAT(r.name), u.name, u.uid, n.title, n.nid, a.timestamp, d.field_video_duration_value AS duration
FROM
db_node_view_count a
join db_node n
ON a.nid = n.nid
JOIN db_field_data_field_video_duration d
ON n.nid = d.entity_id
JOIN db_users u
ON a.uid = u.uid
LEFT JOIN db_users_roles ur
ON u.uid = ur.uid
LEFT JOIN db_role r
ON ur.rid = r.rid
AND u.uid <> 1
LEFT JOIN db_field_data_field_full_name f
ON u.uid = f.entity_id
GROUP BY f.field_full_name_value
ORDER BY u.uid desc

Some users in your (Drupal) database may have more than one role. So where your original query had (simplified a bit) one row per node, the modified query will duplicate the rows for each role of the user.
You might want to modify the query to include
GROUP BY n.nid, u.uid
and change the SELECT field list to include GROUP_CONCAT(r.name) rather than r.name.

Related

Get only those rows where column a has as many duplicate entries, as many there is distinctive values in column b

My current query:
select users.id as user_id, opportunities.id as op_id, opportunities.title, certificates.id as cert_id from opportunities
join opportunity_certificates on opportunities.id=opportunity_certificates.opportunity_id
join certificates on opportunity_certificates.certificate_id=certificates.id
join user_certificates on certificates.id=user_certificates.certificate_id
join users on user_certificates.user_id=users.id
where opportunity_certificates.is_required = 1 and
opportunities.id = 1
This produces the table on the picture below.
cert_id column can have values from 1 to 7, depends on the opportunities.id. In the table below, I want the query to return only the rows which have the same user_id but different cert_id, 1 and 2.
If the table had 3 different cert_id, I would want it to return only the rows which have same user_id but different cert_id, 1,2 and 3.
when the cert_id has only one value, query should return all the records with that one value in cert_id. Basically, it should show all users who have all required certificates.
The query has to be in the current format. I experimented with
group by users.id
having count(*) >
but I don't know how to make that comparison dynamic, relative to the count of distinctive values in the cert_id column.
Compare counts with a having condition.
select u.id as user_id --, o.id as op_id, o.title
from opportunities o
join opportunity_certificates oc on o.id=oc.opportunity_id
join certificates c on oc.certificate_id=c.id
join user_certificates uc on c.id=uc.certificate_id
join users u on uc.user_id=u.id
where oc.is_required = 1 and o.id = 1
group by u.id --,o.id,o.title
having count(distinct c.id)=(select count(distinct id) from certificates)
Useful?
with data as (
select users.id as user_id, o.title, c.id as cert_id
from opportunities o
inner join opportunity_certificates oc on oc.opportunity_id = o.id
inner join certificates c on c.id = oc.certificate_id
inner join user_certificates uc on uc.certificate_id = c.id
inner join users u on u.id = uc.user_id
where oc.is_required = 1 and o.id = 1
)
select user_id, min(title) as title, max(cert_id) as num_certs
from data
group by user_id
having count(cert_id) = (select max(cert_id) from data);
I'm assuming that cert_id values start and 1 and run sequentially. You could also use count(distinct ...) in the having clause but it guess it's debatable which ones expresses you intent more clearly.
If your version of MySQL doesn't support CTEs then you should be able to just drop that whole subquery into the having clause as well.
select u.id as user_id, min(o.title) as title, max(c.cert_id) as num_certs
from opportunities o
inner join opportunity_certificates oc on oc.opportunity_id = o.id
inner join certificates c on c.id = oc.certificate_id
inner join user_certificates uc on uc.certificate_id = c.id
inner join users u on u.id = uc.user_id
where oc.is_required = 1 and o.id = 1
group by u.id
having count(c.cert_id) = (
select max(c.cert_id)
from opportunities o
inner join opportunity_certificates oc on oc.opportunity_id = o.id
inner join certificates c on c.id = oc.certificate_id
inner join user_certificates uc on uc.certificate_id = c.id
inner join users u on u.id = uc.user_id
where oc.is_required = 1 and o.id = 1
);
Here's another one that might work if you have window functions available. (It might work with Laravel better?):
select *
from (
select users.id as user_id, o.title,
count(distinct c.id) over (partition by u.id) as user_certs,
max(c.id) over () as total_certs
from opportunities o
inner join opportunity_certificates oc on oc.opportunity_id = o.id
inner join certificates c on c.id = oc.certificate_id
inner join user_certificates uc on uc.certificate_id = c.id
inner join users u on u.id = uc.user_id
where oc.is_required = 1 and o.id = 1
) t
where user_certs = total_certs;

How to use ORDER BY in a query which is containing JOIN?

I have a query which selects all comments for each post. Here is my query:
SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c
INNER JOIN users u ON c.user_id = u.id
LEFT JOIN votes_comments v ON c.id = v.comment_id
WHERE c.post_id = :id;
Now I want to add ORDER BY c.id to that query. How?
An order by is irrelevant because this query returns one row:
SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c INNER JOIN
users u
ON c.user_id = u.id LEFT JOIN
votes_comments v
ON c.id = v.comment_id
WHERE c.post_id = :id;
This is an aggregation query (because of the SUM()) without a GROUP BY. Such a query always returns one row, even when no rows match the join.
You probably want a GROUP BY. My best guess is:
SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c INNER JOIN
users u
ON c.user_id = u.id LEFT JOIN
votes_comments v
ON c.id = v.comment_id
WHERE c.post_id = :id
GROUP BY c.id, c.content, u.name, u.reputation
ORDER BY c.id;
You can just add the ORDER BY clause at the end:
SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_comments
FROM comments c
INNER JOIN users u ON c.user_id = u.id
LEFT JOIN votes_comments v ON c.id = v.comment_id
WHERE c.post_id = :id
ORDER BY c.id;
By using this query you get only one row which id you put in where clause.
If you want to get one post ordered then you write order by in last.
If you want to get last's comment first so use desc with order by.
SELECT c.id, c.content, u.name, u.reputation, SUM(v.value) AS total_vote_commentFROM comments c INNER JOIN users u ON c.user_id = u.id LEFT JOIN votes_comments v ON c.id = v.comment_id WHERE c.post_id = :id order by id desc;
desc = descending order
asc = ascending order

mysql join with multiple tables and count query

I have total 6 tables in which different info has been saved
Now i need a result in which get count from 5 tables and select all info from main table but if record does not exist than it must be need to return 0 instead of no row found that's the problem here
I have tried below query but didn't get success
SELECT
u.*,
COUNT(DISTINCT c.id) as comments,
COUNT(DISTINCT d.id) as dislikes,
COUNT(DISTINCT l.id) as likes,
COUNT(DISTINCT s.id) as shares,
COUNT(DISTINCT t.id) as tags
FROM
job_details as u
JOIN job_comments as c ON u.id = c.job_id
JOIN job_dislike as d ON u.id = d.job_id
JOIN job_like as l ON u.id = l.job_id
JOIN job_share as s ON u.id = s.job_id
JOIN job_tags as t ON u.id = t.job_id
WHERE
u.id = c.job_id AND
u.id = d.job_id AND
u.id = l.job_id AND
u.id = s.job_id AND
u.id = t.job_id
GROUP BY
u.id
This query is executed, but didn't get exact result.
I don't quite understand why.
I was hoping somebody here could help me out?
Thanks!
You probably didn't get the exact result because some tables may be missing values.
Although you can solve this problem with a LEFT JOIN, the safer solution is to pre-aggregate the data:
SELECT u.*, c.comments, d.dislikes, l.likes, s.shares, t.tags
FROM job_details as u LEFT JOIN
(select c.job_id, count(*) as comments from job_comments group by c.job_id
) c
ON u.id = c.job_id LEFT JOIN
(select d.job_id, count(*) as dislikes from job_dislike d group by d.job_id
) d
ON u.id = d.job_id LEFT JOIN
(select l.job_id, count(*) as likes from job_like l group by l.job_id
) l
ON u.id = l.job_id LEFT JOIN
(select s.job_id, count(*) as shares from job_share s group by s.job_id
) s
ON u.id = s.job_id LEFT JOIN
(select t.job_id, count(*) as tags from job_tags t group by t.job_id
) t
ON u.id = t.job_id;
Why is this better? Consider an id that has 5 comments, likes, dislikes, shares and tags. The JOIN approach produces an intermediate result with 5*5*5*5*5 = 3,125 intermediate rows. Things can really get out of hand for popular ids.
Use LEFT JOIN instead of JOIN. and you don't need WHERE clause since you have joined those tables. And, use IFNULL function to return 0 for null values. You need to modify you query like this :
SELECT u.id,
IFNULL(COUNT(DISTINCT c.id),0) as comments,
IFNULL(COUNT(DISTINCT d.id),0) as dislikes,
IFNULL(COUNT(DISTINCT l.id),0) as likes,
IFNULL(COUNT(DISTINCT s.id),0) as shares,
IFNULL(COUNT(DISTINCT t.id),0) as tags
FROM job_details as u
LEFT JOIN job_comments as c ON u.id = c.job_id
LEFT JOIN job_dislike as d ON u.id = d.job_id
LEFT JOIN job_like as l ON u.id = l.job_id
LEFT JOIN job_share as s ON u.id = s.job_id
LEFT JOIN job_tags as t ON u.id = t.job_id
GROUP BY u.id

MySQL select where no matches in join

How would I do following in MySQL:
I have 3 tables:
user: id
communication: id, creation_date
user_communication: user_id, communication_id
Now I want to select all users that have had no communication since a given date.
Following is what I have now, but I'm stuck on how to get what I described above.
SELECT DISTINCT u.id FROM user u
LEFT JOIN user_communication uc ON uc.user_id = u.id
LEFT JOIN communication c ON c.id = uc.communication_id
WHERE c.creation_date < '2013-8-1';
The where condition is undoing the left join. The initial solution would be to move it to the on clause:
SELECT DISTINCT u.id FROM user u
LEFT JOIN user_communication uc ON uc.user_id = u.id
LEFT JOIN communication c ON c.id = uc.communication_id and c.creation_date < '2013-8-1';
But this doesn't do what you want. This retrieves all records. If you had a creation date field in the select clause, it would be NULL when there is record before that date.
For no communication since that date, you can do a "double" negative" query. Look for records that are since that date, and return the mismatches:
SELECT DISTINCT u.id
FROM user u LEFT JOIN
user_communication uc
ON uc.user_id = u.id LEFT JOIN
communication c
ON c.id = uc.communication_id and c.creation_date >= '2013-08-01'
WHERE c.creation_date is NULL;
EDIT:
I see. The problem is a little more subtle than my answer above. Each user has multiple communications, so none can be later. The following query tests this by grouping by u.id and then checking that there are no non-NULL values from the above join:
SELECT u.id
FROM user u LEFT JOIN
user_communication uc
ON uc.user_id = u.id LEFT JOIN
communication c
ON c.id = uc.communication_id and c.creation_date >= '2012-08-01'
group by u.id
having min(c.creation_date is null) = 1;
SELECT DISTINCT u.id FROM user u
LEFT JOIN user_communication uc ON uc.user_id = u.id
LEFT JOIN (SELECT * FROM communication WHERE creation_date < '2013-8-1') c
ON c.id = uc.communication_id
WHERE c.id is NULL;
After some research and help I have following query, which seems to work:
SELECT DISTINCT(u.id)
FROM user u
WHERE (SELECT coalesce(max(c.creation_date), '1900-01-01 00:00:00') last_creation_date
FROM user inneru
LEFT JOIN user_communication uc ON uc.user_id = inneru.id
LEFT JOIN communication c ON c.id = uc.communication_id
WHERE inneru.id = u.id) < '2012-08-01'
SQLFiddle: http://sqlfiddle.com/#!2/5dfad/10

MYSQL union with many JOIN

I'm trying to write a query to fetch a listing from 2 (list1,list2)tables with the same columns.
Are there any other way to rewrite this code?
(SELECT r.id as rid, s.title, u.username
FROM list1 r
JOIN drama s ON r.parent_id = s.id
LEFT JOIN image i ON s.image_id = i.id
LEFT JOIN user u ON r.user_id = u.user_id)
UNION ALL
(SELECT r.id as rid, s.title, u.username
FROM list2 r
JOIN movie s ON r.parent_id = s.id
LEFT JOIN image i ON s.image_id = i.id
LEFT JOIN user u ON r.user_id = u.user_id)
ORDER BY rid LIMIT 10
whats wrong if you do this
SELECT r.id as rid, m.title AS movie Title,
d.title as DramaTitle, u.username
FROM list1 r
INNER JOIN movie m ON r.parent_id = m.id
INNER JOIN drama d ON r.parent_id = d.id
LEFT JOIN image i ON s.image_id = i.id
LEFT JOIN user u ON r.user_id = u.user_id
ORDER BY r.id LIMIT 10
SELECT r.id as rid, s.title, u.username
FROM (SELECT l1.id, l1.user_id, l1.parent_id FROM list1 l1
UNION ALL
SELECT l2.id, l2.user_id, l2.parent_id FROM list2 l2) r
INNER JOIN drama s ON r.parent_id = s.id
LEFT JOIN image i ON s.image_id = i.id
LEFT JOIN user u ON r.user_id = u.user_id
ORDER BY rid
LIMIT 10