I have Two tables: left one is users_projects, right one is projects:
I want to select the projects that user 3 is not participating in (only p_ID 5 and 7).
I've tried SELECT * FROM users_projects up INNER JOIN projects p ON p.p_ID=up.p_ID WHERE up.u_ID!=3
but that also returns me p_ID 1 which both user 2 and 3 are a part of.
Thanks for your help!
A solution with LEFT JOIN:
SELECT
*
FROM
projects p LEFT JOIN users_projects up ON (p.p_ID = up.p_ID AND up.u_ID = 3)
WHERE
up.u_ID IS NULL
Basically select all Projects and join them with the user_projects of the desired user. Left join makes all rows from the project table appear even if the is no corresponding row in the users_projects table. These rows have all fields from the users_projects set to NULL, so we can just select those.
This is not a JOIN query, but a query with a non-correlated sub-select with a NOT IN() predicate.
I hope the columns of the projects table are enough ...
SELECT
*
FROM
( SELECT 1,'Apple' -- input data, don't use in 'real' query
UNION ALL SELECT 5,'Banna' -- input data, don't use in 'real' query
UNION ALL SELECT 7,'Carrot' -- input data, don't use in 'real' query
UNION ALL SELECT 8,'Durian') -- input data, don't use in 'real' query
projects(p_id,p_name)
WHERE p_id NOT IN (
SELECT
p_id
FROM
( SELECT 2,1 -- input data, don't use in 'real' query
UNION ALL SELECT 2,5 -- input data, don't use in 'real' query
UNION ALL SELECT 2,7 -- input data, don't use in 'real' query
UNION ALL SELECT 3,1 -- input data, don't use in 'real' query
UNION ALL SELECT 3,8) -- input data, don't use in 'real' query
users_projects(u_id,p_id)
WHERE u_id=3
)
;
p_id|p_name
7|Carrot
5|Banna
Related
How to write a query correctly to get data without uniqueness?
I have list of ids, where ids are repeated.
Example: (1,1,1,2,3)
select *
from table
where id in (1,1,1,2,3);
returns only (1,2,3).
But I need to get with repeated entries.
Use a derived table and left join:
select t.*
from (select 1 as id union all select 1 union all select 1 union all select 2 union all select 3
) i left join
t
on t.id = i.id
The syntax for the derived table might vary depending on the database, but most support the above syntax.
That's not what WHERE statement is for, as it's only for filtering matching keys.
If you need to do that in this order, use sth like
select table.*
from (
select 1 as id
union select 1
union select 1
union select 2
union select 3
) myStaticKeys
join table using (id)
I want the count even if the count is 0. My current query is
SELECT `id`,count(0) as `fetchpc` FROM `user` WHERE pid in('4,6,7,8') GROUP BY `id`
But it returns only those id where count is greater than 0
Edit:
the values used for in('4,6,7,8') are first fetched from database in another query. And then using a script rows are converted to 4,6,7,8.
So all the values are present in the database.
Also it is possible that the values returned can go upto 100+ values.
You could left join this query on a "fictive" query that queries these IDs as literals:
SELECT ids.id, COALESCE(cnt, 0)
FROM (SELECT 4 AS id
UNION ALL
SELECT 6 AS id
UNION ALL
SELECT 7 AS id
UNION ALL
SELECT 8 AS id) ids
LEFT JOIN (SELECT id, COUNT(*) AS cnt
FROM fetchpc
GROUP BY id) t ON t.id = ids.id
You can use a derived table. I would recommend:
SELECT i.id, COUNT(u.id) as fetchpc
FROM (SELECT 4 as id UNION ALL
SELECT 6 as id UNION ALL
SELECT 7 as id UNION ALL
SELECT 8 as id
) i LEFT JOIN
`user` u
ON u.id = i.id
GROUP BY i.id;
From a performance perspective, this is much better than aggregating first (in a subquery) and then joining. Basically, the aggregation (in that case) has to aggregate all the data and afterwards filter out the unnecessary rows.
This formulation filters the rows first, which should speed the aggregation.
I want to extract some information from two different table in one database,
[(first table): id-nbrNight-........]
[(second table): id-........]
I want to extract the nbrNight from the first table & the id from the second table:
so in my case I write this, but I don't know how to rassemble this two line in one line:
SELECT sum(nbrNight) as night FROM firsttab
SELECT count(`id`) as id FROM secondtab
I wirte this to rassemble this two line:
SELECT sum(nbrNight) as night,count(`id`) FROM firsttab,secondtab
But it doesn't work!
You can use UNION to combine the result from two query like
SELECT sum(nbrNight) as night FROM firsttab
UNION
SELECT count(`id`) as id FROM secondtab
(OR) do a JOIN with both tables using a common column between them (if any present) like below (assuming id is the common column between them)
SELECT sum(t1.nbrNight) as nightsum, count(t2.`id`) as idcount
FROM firsttab t1 JOIN secondtab t2 ON t1.id = t2.id
One option is to use the queries as inline views; reference those queries as a rowsource (like a table) in another query.
Since each query returns a single row, you can safely perform a JOIN operation, without need for any join predicate (aka CROSS JOIN).
For example:
SELECT f.night
, s.id
FROM ( SELECT SUM(nbrNight) AS night FROM firsttab ) f
CROSS
JOIN ( SELECT COUNT(id) AS id FROM secondtab ) s
Another option (since both queries are guaranteed to return exactly one row, if they don't return an error) is to include the query in the SELECT list of another query. It's not necessary to include a column alias in the subquery, but we can assign an alias.
For example:
SELECT ( SELECT SUM(nbrNight) FROM firsttab ) AS night
, ( SELECT COUNT(id) FROM secondtab ) AS id
If either of the queries were returning more than one column, then the approach in the first example will still work. The inline view queries can return multiple expressions, and we can reference those expressions in the outer query. With the pattern in the second example, that imposes a restriction that the subqueries must return only one expression (one column).
As an example to demonstrate an inline view returning more than one column, the inline view f returns three expressions:
SELECT f.night
, f.cnt
, f.min_nbr
, s.id
FROM ( SELECT SUM(nbrNight) AS night
, COUNT(nbrNight) AS cnt
, MIN(nbrNight) AS min_nbr
FROM firsttab
) f
CROSS
JOIN ( SELECT COUNT(id) AS id FROM secondtab ) s
I have a "server" table which has a column named 'SN' in mysql, when do query to retrive servers with some sns from 'sn1' to 'sn10000', we can:
select * from server where sn in ('sn1','sn2','sn3',...'sn10000');
If there is only one sn in 'sn1'-'sn10000' which not exists in database, then the query above will retrive 9999 rows of result.
The question is how can I easily get which one in 'sn1'-'sn10000' is not exists in database except the additional work, such as handling the result with shell script etc.
I have an ugly sql like below can use:
select * from (select 'sn1' as sn
union select 'sn2'
union select 'sn3'
....
union select 'sn10000') as SN
where not exists (select id from server where server.sn=SN.sn);
Is Anyone has other better methods? Thanks.
Your query is perfectly fine for the intended use, but on MySQL the NOT IN and LEFT JOIN/IS NULL are more effecient that NOT EXISTS. Here are your alternatives:
NOT IN
SELECT *
FROM ( SELECT 'sn1' as sn
UNION ALL SELECT 'sn2'
UNION ALL SELECT 'sn3'
....
UNION ALL SELECT 'sn10000') as SN
WHERE sn.sn NOT IN (SELECT s.id FROM SERVER s)
LEFT JOIN/IS NULL
SELECT s.id
FROM SERVER s
LEFT JOIN ( SELECT 'sn1' as sn
UNION ALL SELECT 'sn2'
UNION ALL SELECT 'sn3'
....
UNION ALL SELECT 'sn10000') as SN ON SN.sn = s.id
WHERE sn.sn IS NULL
You might notice I used UNION ALL, rather than UNION - UNION removes duplicates (which won't happen in your example), making it slower so UNION ALL is a better choice.
Stick your sn1, sn2, sn3... sn10000 values in a temporary table, and then use Joins.
Select server.* from server inner join tempt on (tempt.value = server.sn)
will give you the ones that match, where as
Select sn.* from server right outer join tempt on (tempt.value = server.sn)
where server.somefield is Null
should take care of finding the missing ones.
I want to calculate how many unique logins from 2 (or probably more tables).
I tried this:
SELECT count(distinct(l1.user_id))
FROM `log_1` l1
LEFT JOIN `log_2` l2
ON l1.userid = l2.userid;
But it gives me result of l1. If I didn't put l1 on li.userid (distinct), it said "ambiguous".
How do I combine the table, and then select unique login of the combined table?
EDIT:
Tested: I test the count(distinct(l1.userid)) and count(distinct(l2.userid)). It gives me different result
If you are using LEFT JOIN then you will get at least one row in the combined result for each row in l1, so the join is entirely unnecessary if you just want a distinct count. This would give you the same result as your query:
SELECT count(distinct(l1.user_id))
FROM `log_1` l1
Perhaps you want an INNER JOIN or UNION instead? A UNION will count a user if they appear in either table. An INNER JOIN will count them only if they appear in both tables. Here's an example of the UNION:
SELECT count(*) FROM (
SELECT distinct(user_id) FROM `log_1`
UNION
SELECT distinct(user_id) FROM `log_2`
) T1