SQL join two queries - sql

I am a bit lost here. I would like to join these two queries into one to avoid two connections and simplify the code.
"SELECT uname FROM Projects WHERE id IN (SELECT MAX(id) FROM Projects)"
"SELECT name FROM Users WHERE username like"+"'"+ uname +"'"
Right now I am using two queries and taking the result of the first into the second one.
I am sure the two queries can become one but I do not know how to do it.

You can simply use = rather than LIKE since I you are not using pattern symbol such as %.
SELECT a.name
FROM Users a
INNER JOIN Projects b
ON a.username = b.uname
WHERE b.ID = (SELECT MAX(id) FROM Projects)

i think the following query will work:
SELECT name FROM Users WHERE username in
(SELECT uname FROM Projects WHERE id IN
(SELECT MAX(id) FROM Projects))

You may try like this using the INNER JOIN considering that both of your tables are linked through User_ID
SELECT u.name
FROM Users u INNER JOIN Projects p ON u.username = p.uname
WHERE p.ID = (SELECT MAX(id) FROM Projects)

Related

Remove duplicates from result in sql

i have following sql in java project:
select distinct * from drivers inner join licenses on drivers.user_id=licenses.issuer_id
inner join users on drivers.user_id=users.id
where (licenses.state='ISSUED' or drivers.status='WAITING')
and users.is_deleted=false
And result i database looks like this:
And i would like to get only one result instead of two duplicated results.
How can i do that?
Solution 1 - That's Because one of data has duplicate value write distinct keyword with only column you want like this
Select distinct id, distinct creation_date, distinct modification_date from
YourTable
Solution 2 - apply distinct only on ID and once you get id you can get all data using in query
select * from yourtable where id in (select distinct id from drivers inner join
licenses
on drivers.user_id=licenses.issuer_id
inner join users on drivers.user_id=users.id
where (licenses.state='ISSUED' or drivers.status='WAITING')
and users.is_deleted=false )
Enum fields name on select, using COALESCE for fields which value is null.
usually you dont query distinct with * (all columns), because it means if one column has the same value but the rest isn't, it will be treated as a different rows. so you have to distinct only the column you want to, then get the data
I suspect that you want left joins like this:
select *
from users u left join
drivers d
on d.user_id = u.id and d.status = 'WAITING' left join
licenses l
on d.user_id = l.issuer_id and l.state = 'ISSUED'
where u.is_deleted = false and
(d.user_id is not null or l.issuer_id is not null);

Making queries with two different tables in SQL/DBMS using basic relation algebra

I am new to DBMS and SQL. I need to run a query that uses two tables. For example, I have a table of users[ name, password, id, companyId] and another table of companies[ comp_name, companyID, netWorth]. companyId links the two tables. For every user, I need to make a query that returns their name, comp_name, and netWorth using basic rel alg operations.
A simple join should do the trick:
SELECT u.name, c.comp_name, c.net_worth
FROM users u
JOIN companies c ON u.company_id = c.company_id
This is the Query you are looking for
(Just used the =, no INNER JOIN ) ; )
SELECT users.name, companies.comp_name, companies.netWorth
FROM companies, users
WHERE companies.companyID = users.companyId

SQL IN query from multiple tables

SELECT DISTINCT addresses.email FROM addresses
WHERE addresses.user_id IN (SELECT user_group.id_user_groups FROM user_group
WHERE id_group_groups IN (SELECT news_group.groupid_newsg FROM news_group
WHERE newsid_news_good=1))
The above mentioned SQL query is not executing! It gets hanged until I stop the query. I have tried SQL operator "UNION" after first SELECT statement, but it displays all the email addresses which does not belong to a group. I want to select only those email addresses of the users who belong to "id_group_groups =5" (pls see the query below ) and are subscribed to "newsid_news_good=1".
The following query runs perfectly fine:
SELECT DISTINCT addresses.email FROM addresses
WHERE addresses.user_id IN (SELECT user_group.id_user_groups FROM user_group
WHERE id_group_groups =5 )
Does anybody have an idea what is the problem with the first query? Help will be strongly appreciated!
I think the sub selects complicate your problem. If I understand it right, it would be easier to solver your problem using joins instead of sub selects.
Try out something like this:
SELECT DISTINCT addresses.email
FROM addresses
JOIN user_group
ON user_group.id_user_groups = adresses.USER_ID
JOIN news_group
ON news_group.groupid_newsg = user_group.id_group_groups
WHERE newsid_news_good = 1
SELECT DISTINCT addresses.email FROM addresses
INNER JOIN (
SELECT user_group.id_user_groups FROM user_group
INNER JOIN news_group
ON news_group.groupid_newsg = id_group_groups
WHERE newsid_news_good=1
)
ON user_group.id_user_groups = addresses.user_id
You want to use joins. The subqueries you are using are most likely the cause of your performance woes.
SELECT DISTINCT a.email
FROM addresses a
INNER JOIN user_group u ON u.id_user_groups AND u.id_group_groups = 5
INNER JOIN news_group n ON n.groupid_newsg = u.id_group_groups AND n.newsid_news_good = 1
I'm going to guess that you are using MySQL, because it does a really poor job of executing subqueries in unions. The canonical way to fix this is to change them to exists with correlated subqueries:
SELECT DISTINCT a.email
FROM addresses a
where exists (select 1
from user_group ug
where ug.id_user_groups = a.user_id and
exists (select 1
from news_group ng
where ng.newsid_news_good = 1 and
ng.groupid_news = ug.id_group_groups
)
)
This solution works in all databases, of course; it is much more efficient in MySQL. Assuming email is not repeated in the addresses table, then you can drop the outer distinct.
The alternatives with join are also feasible. However they require the distinct.

SQL Query - Multiple Joins on Same field

I need assistance building this query where i need to select different values from same table but different Unique Keys.
To elaborate more ill provide the below example:
I have 2 tables:
Issues (IssueID, AuthorID_FK, AssigedID_FK, ... )
Users (UserID, User_Label, ... )
Both AuthorID_FK & AssigedID_FK are linked to table Users and i need to get in the same query result the User_Label for both.
Can you please assist?
Thanks,
SELECT a.IssueID, b.User_Label, c.User_Label FROM Issues a
INNER JOIN USERS b on a.AuthorID_FK = b.UserID
INNER JOIN USERS c on a.AssignedID_FK = c.UserID
something like that :) This should work in MS SQL Server
Well, this one should work too :)
SELECT IssueID, U.User_Label FROM Issues I
INNER JOIN Users U ON U.UserID = I.AuthorID_FK
UNION
SELECT IssueID, U.User_Label FROM Issues I
INNER JOIN Users U ON U.UserID = I.AssigedID_FK
Wont
SELECT a.IssueID, b.UserID
FROM Issues a
JOIN Users b ON (a.AuthorID_FK=b.UserID OR a.AssignedID_FK = b.UserID)
work?
You may want to try something like this
SELECT
issues.IssueID,
Authour.User_Label AS Author_Label,
Assigned.User_Label AS Assigned_user_Label
FROM
issues
INNER JOIN users AS Authour ON Authour.UserID = issues.AuthorID_FK
INNER JOIN users AS Assigned ON Assigned.UserID = issues.AssignedID_FK

Complex join with nested group-by/having clause?

I ultimately need a list of "import" records that include "album"
records which only have one "song" each.
This is what I'm using now:
select i.id, i.created_at
from imports i
where i.id in (
select a.import_id
from albums a inner join songs s on a.id = s.album_id
group by a.id having 1 = count(s.id)
);
The nested select (with the join) is blazing fast, but the external
"in" clause is excruciatingly slow.
I tried to make the entire query a single (no nesting) join but ran
into problems with the group/having clauses. The best I could do was
a list of "import" records with dupes, which is not acceptable.
Is there a more elegant way to compose this query?
How's this?
SELECT i.id,
i.created_at
FROM imports i
INNER JOIN (SELECT a.import_id
FROM albums a
INNER JOIN songs s
ON a.id = s.album_id
GROUP BY a.id
HAVING Count(* ) = 1) AS TEMP
ON i.id = TEMP.import_id;
In most database systems, the JOIN works a lost faster than doing a WHERE ... IN.
SELECT i.id, i.created_at, COUNT(s.album_id)
FROM imports AS i
INNER JOIN albums AS a
ON i.id = a.import_id
INNER JOIN songs AS s
ON a.id = s.album_id
GROUP BY i.id, i.created_at
HAVING COUNT(s.album_id) = 1
(You might not need to include the COUNT in the SELECT list itself. SQL Server doesn't require it, but it's possible that a different RDBMS might.)
Untested:
select
i.id, i.created_at
from
imports i
where
exists (select *
from
albums a
join
songs s on a.id = s.album_id
where
a.import_id = i.id
group by
a.id
having
count(*) = 1)
OR
select
i.id, i.created_at
from
imports i
where
exists (select *
from
albums a
join
songs s on a.id = s.album_id
group by
a.import_id, a.id
having
count(*) = 1 AND a.import_id = i.id)
All three sugested techniques should be faster than your WHERE IN:
Exists with a related subquery (gbn)
Subquery that is inner joined (achinda99)
Inner Joining all three tables (luke)
(All should work, too ..., so +1 for all of them. Please let us know if one of them does not work!)
Which one actually turns out to be the fastest, depends on your data and the execution plan. But an interesting example of different ways for expressing the same thing in SQL.
I tried to make the entire query a
single (no nesting) join but ran into
problems with the group/having
clauses.
You can join subquery using CTE (Common Table Expression) if you are using SQL Server version 2005/2008
As far as I know, CTE is simply an expression that works like a virtual view that works only one a single select statement - So you will be able to do the following.
I usually find using CTE to improve query performance as well.
with AlbumSongs as (
select a.import_id
from albums a inner join songs s on a.id = s.album_id
group by a.id
having 1 = count(s.id)
)
select i.id, i.created_at
from imports i
inner join AlbumSongs A on A.import_id = i.import_id