I have two tables like these:
Table "users":
user_id | source
----------------
1 | 2
2 | 2
3 | 3
4 | 0
Table "sources":
source_id | name
----------------
1 | "one"
2 | "two"
3 | "three"
4 | "four"
Now I need to SELECT (*) FROM source and additionally COUNT "users" that have this source, BUT if there is an additional filter(requests by PHP mysqli), then additionally sort "sources" table by its users count.
What is the best way to do so, and is it possible to do in one statement?
--------------Added editing----------
The first part(SELECT with count from another table) I'm doing this way:
SELECT
id, name
(select count(*) from users where source = sources.id) as sourceUsersCount
FROM sources
And now, how to order this list by users count in each source?
Please check the below query if this is what you need.
select s.*,a.c from sources s
left join
(select count(*) as c,source as src
from user u join sources s
on s.source_id = u.source group by u.source) a
on s.source_id = a.src;
Count the number of users:
SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
GROUP BY sources.source_id;
I assume by filters you mean the WHERE clause:
SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
WHERE sources.source_id = 2
GROUP BY sources.source_id;
And you can always attach an ORDER BY on the end for sorting:
SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
GROUP BY sources.source_id
ORDER BY sources.source_id DESC;
Achieved it by doing so:
SELECT
sources.*,
count(users.source) as sourceUsersCount
FROM sources
LEFT JOIN users ON sources.id = users.source
//In case of additional filters
WHERE
id != 0 AND (name LIKE %?% OR id LIKE %?%)
//\\
GROUP BY sources.id
//In case of sorting by "users" count
ORDER BY sourceUsersCount ASC
//\\
Is it the best way, or maybe there are some faster variants?
Related
I would like to append the results of 2 queries into one result set.
SELECT n.member_no, n.surname, n.first_name
FROM `names` AS n
WHERE member_no = '1003';
SELECT s.registration
FROM `system` AS s
WHERE s.RECNUM = 1;
This must return one record with data from the names table plus data from the system (one record) table
Member_no | surname | first_name | registration
--------------------------------------------------
1003 | Brown | Peter | My registration
You can use CrossJoin:
SELECT n.member_no, n.surname, n.first_name, s.registration
FROM names AS n
CROSS JOIN system s
WHERE n.member_no = '1003' and s.RECNUM = 1;
we can correlate your registration and name tables based on row_number(). You may want to try below query.
SELECT rn.member_no, rn.surname, n.first_name, s.registration
FROM
(SELECT member_no, surname, first_name, row_number() over (order by member_no) rn
FROM `names`) n
LEFT JOIN
(SELECT row_number() over (order by RECNUM) rn, registration
FROM `system`) s on s.rn = n.rn
WHERE n.member_no = '1003'
Try this one.
SELECT DISTINCT n.member_no, n.surname, n.first_name,s.registration
FROM `names` AS n, `system` AS s
WHERE s.RECNUM = 1 AND member_no = '1003';
I just wrote this query for my tables: NEWS and NEWS-CATEGORIES in order to count the items of each category:
SELECT DISTINCT CAT.cid, CAT.c_title, N.n_category, count(*) AS cat_count
FROM news N
inner join news - categories CAT
on CAT.cid = N.n_category
GROUP BY N.n_category
but the problem is that it just shows me the categories which contains news! but I wana get all of the categories even the ones with empty news...
my NEWS table is:
nid | n_category | etc
my NEWS-CATEGORY table is:
cid | c_title | etc
Thanks for your help
Regards
Try this:
SELECT
CAT.cid,
CAT.c_title,
count(N.n_category) AS cat_count
FROM `news-categories` CAT
LEFT JOIN `news` N
ON CAT.cid = N.n_category
GROUP BY CAT.cid,
CAT.c_title
Use LEFT JOIN:
SELECT CAT.cid, CAT.c_title, IFNULL(COUNT(N.n_category), 0) AS cat_count
FROM `news-categories` AS CAT
LEFT JOIN news AS N ON CAT.cid = N.n_category
GROUP BY CAT.cid
Things to note: 1) You have to use a column from news in the COUNT() expression, not COUNT(*), so that the null match is not counted. 2) There's no need to select N.n_category, since that's always equal to CAT.cid and you're already selecting that. 3) The GROUP BY column has to be from the news-categories table -- you can't group by a column in the table that may not have any matching rows, since that value will always be NULL.
I'm just going to point out that you can do this with a subquery as well:
SELECT CAT.cid, CAT.c_title,
(SELECT COUNT(*) FROM news N WHERE CAT.cid = N.n_category)
FROM `news - categories` CAT;
Under some circumstances, this can even have better performance.
I have a query which give result like
id | productid | userid | coinsid
1 | 2 | 2 | 5
3 | 2 | 2 | 6
4 | 2 | 3 | 7
5 | 2 | 4 | 8
6 | 2 | 3 | 9
This is result for specific productid. Now i have to update the balance in user table by adding $1 to all the users in above result, but if userid is twice, i need to add $1 twice to the balance of that specific user. So in the above case $1 twice added to userid=2 balance and userid=3 balance.
The simple way is to count records for every distinct userid and run queries as many time as we have users in foreach loop. But i am looking for some optimize way. Please suggest any. Thanks
One approach:
UPDATE user_table u
JOIN ( SELECT q.userid
, SUM(1.00) AS deposit
FROM (
-- original OP query goes here
) q
GROUP BY q.userid
) r
ON r.userid = u.userid
SET u.balance = u.balance + r.deposit
We use the original OP query that returns the resultset displayed, and make that an inline view (aliased in the query above as q).
From that, we query a distinct list of userid, and the number of times that userid appears in the resultset. That gives us the username and a deposit amount (1 dollar for each time the userid appears) (some databases might want us to specify the value as 1.0 rather than 1, to make sure it was decimal. I think the SUM is more representative of what we are trying to accomplish.)
We join that inline view (r) to the user table, and add the deposit amount to the current balance, for that user (assuming the balance is stored as decimal dollars (1.00 = one dollar)
To testing, convert the UPDATE into a SELECT statement:
remove the "SET" clause
add an "ORDER BY" clause (optional) to make the results determinate
remove the "UPDATE" keyword and replace it
with:
SELECT r.userid
, r.deposit
, u.balance AS old_balance
, u.balance + r.deposit AS new_balance
, u.userid
FROM
Full select:
SELECT r.userid
, r.deposit
, u.balance AS old_balance
, u.balance + r.deposit AS new_balance
, u.userid
FROM user_table u
JOIN ( SELECT q.userid
, SUM(1.00) AS deposit
FROM (
-- original OP query goes here
) q
GROUP BY q.userid
) r
ON r.userid = u.userid
NOTE There is no WHERE clause, the JOIN predicates (in the ON clause) is what determines which rows are selected/affected in the user table.
Assuming you have no duplicate user ids in your balance table, maybe something like this would work:
update balance_table set balance_table.balance = (select count(*) from users_table where users_table.user_id = balance_table.user_id) * 1;
I haven't tried this query against a mysql database as I am more familiar with plsql, but wouldn't something like this work ?
The correlated subquery in the other answer will work, but an INNER JOIN will usually be more efficient. Try something like this; you'll of course need to supply the table and column names.
UPDATE myTable
INNER JOIN (
SELECT userid, count(*) AS AmountToAdd
FROM users
GROUP BY userid
) UserCounts ON myTable.userid = UserCounts.userid
SET balance = balance + UserCounts.AmountToAdd
select count(*), userid from yourTable group by userid
If I do understand your question.
So lets say i have 2 tables.
table users:
id | name | date
table weight_tracking;
id | user_id | previous_weight | current_weight | date
weight_tracking table is being updated daily with user current weight and previous_weight.
I am trying to display all users ordering by previous_weight - current_weight (so by the difference in weight - who ever lost the most weight will show up first)
Can that be done with 1 call ?
SELECT users.*, weight_tracking.*
FROM users left join weight_tracking on users.id = weight_tracking.user_id
ORDER BY previous_weight - current_weight desc
if a user can have more than one row in weight_tracking table, you could use something like this:
SELECT users.*
FROM users left join weight_tracking on users.id = weight_tracking.user_id
GROUP BY users.id
ORDER BY max(previous_weight) - min(current_weight) desc
I have 2 tables:
users
user_id | user_name | user_avatar
and
events
event_id | event_name | event_avatar
i need a query that will select all avatars in one array, and then, i want to echo them all, as a photo gallery.
can anyone help me please ?
i've tried
SELECT e.event_avatar , u.user_avatar as img FROM events e ,users u ORDER BY e.id DESC LIMIT 0, 17"
For the SQL bit it seems you want a Union:
Select
event_avatar
From
events
Union All
Select
user_avatar
From
users