Could you please help with this query? I just have started learning SQL, I cannot see where my mistake is.
I have tables : USERS (columns: id, firstname and surname) and POSTS(columns:id, user_id and BODY).
I want to have a joined table which would reflect the count of users that have posted at least 2 times.
So I created a table POSTSBYNUMBER. Then I used INSERT as follows:
INSERT INTO POSTSBYNUMBER
SELECT USERS.FIRSTNAME, USERS.LASTNAME, COUNT(*) AS POSTS_NUMBER
from USERS
JOIN POSTS ON USERS.ID = POSTS.USER_ID
GROUP BY POSTS.USER_ID
HAVING COUNT(*) >= 2;
The table looks all right: has columns FIRSTNAME, SECONDNAME and Posts_Numbers.
But when (using java), I added two new posts for a third user, the post is reflected in table POSTS, but not in POSTSBYNUMBER. Is there any issue with how I have written joining tables in SQL?
An INSERT happens once when you run it. You would seem to want a view instead:
CREATE VIEW POSTSBYNUMBER AS
SELECT u.FIRSTNAME, u.LASTNAME, COUNT(*) AS POSTS_NUMBER
FROM USERS u JOIN
POSTS p
ON u.ID = p.USER_ID
GROUP BY u.FIRSTNAME, u.LASTNAME
HAVING COUNT(*) >= 2;
A view is a "stored query". So, the query runs when you execute it. That way, the data is always up-to-date.
Notice that I also fixed the GROUP BY so it is consistent with the unaggregated SELECT columns.
Related
I have a users table and a pic_urls table, and I want to extract data from several users. Each user may have several rows in the pic_urls table. This is the SQL I have so far:
SELECT
users.id,
users.firstname,
users.lastname,
pic_urls.url
FROM users
JOIN pic_urls
ON users.id = pic_urls.user_id
WHERE users.id != ?
So far I get all the info I want from the users table, but only the last row of pic_urls for each user. My question is, how to group several rows of the pic_urls table (a user usually have several pics) into an array or something?
One option uses a correlated subquery:
select u.id, u.firstname, u.lastname,
(
select json_arrayagg(pu.url)
from pic_urls pu
where pu.user_id = u.id
) all_urls
from users u
This aggregates all pic urls in a json array on each user row. Other aggregate options are available, such as group_concat() for string aggregation.
I'm assuming there's a way to do this with MySQL but my experience with relational databases is limited so I'm hoping to get some guidaince.
I have a users, registrations and user_registrations table. I'm want to create a SELECT query on my users table that does a nested select that counts the user_registrations for that user.
So for example, I would be looking to have something like this:
SELECT *, (SELECT COUNT() FROM user_registrations WHERE users.user_id = user_registrations.user_id) FROM users
I think my understanding of nested selects is off and I'm hoping someone could point me in the right direction here. Thanks.
You need to group and include all columns you select from the users table into your group by clause also
SELECT u.id, u.name, COUNT(r.user_id)
FROM users u
LEFT JOIN user_registrations r ON u.user_id = r.user_id
GROUP BY u.id, u.name
Suppose I have two tables, users and posts. Posts has the following fields, userid, postid, etc and userid can appear multiple times as one user can write multiple posts....I'm just trying sort the users table based off the # of occurrences per userid in the posts table. I can get the # of occurrences per user using this
SELECT userid, COUNT(*)
FROM posts
GROUP BY userid;
I would like to use the values under COUNT(*) column, maybe add it to my other table because then I can simply to something like this
SELECT * FROM users
ORDER BY newcolumn ASC;
but I'm having trouble doing that. Or can I do it without having to add an extra column? Hints please. Thanks
Left join is the key here!
SELECT users.userid,count(posts.userid) AS total_count
FROM users
LEFT JOIN posts on posts.userid = users.userid
GROUP BY users.userid
ORDER BY total_count DESC;
We are taking the left join on two tables with same user_id and we are counting the total number of posts per user using group by. Finally sort by count and show results.
try an left join:
select users.userid, [user fields],count(postid) as posts_count
from users
left join posts on posts.userid = users.userid
group by users.userid,[user fields]
order by posts_count desc.
You want to select users (FROM users) but you want to sort based on criteria in another table (COUNT(*) FROM posts) -- therefore you need to use a JOIN
Off-hand I can't seem to recall if "JOIN" or "RIGHT JOIN" or "FULL JOIN" is what you need if you wanted to get a cartesian product of the tables then group and aggregate on a single field, but I can avoid the need to remember with a subquery (hopefully someone will soon post a smaller and smarter answer):
SELECT users.* FROM users
JOIN (
SELECT userid, COUNT(*) as count
FROM posts
GROUP BY userid
) as subquery ON users.id = subquery.userid
ORDER BY subquery.count
Note: I haven't tested this query, but it looks good to me. Again: hopefully someone will post a better answer soon as I'm not doing my due dilligence, but you definitely need a JOIN :)
You could add a post_count column to the users table, but you would also have to update that count column every time a user creates a new post and you would have to build that logic into your application.
Otherwise, it looks like the answer from FallAndLearn will get you what you need.
I have two tables and they are as follows:
USERS
ORDERS
I want select all users who have at least 1 order or more in the ORDERS table. I know there is an inline query for this in MySQL, but right now I have to select all users and then make another query seeing if each user has an order - all this using a PHP loop.
What I am doing now is not ethically correct, so I basically just want to select all users who have been referenced in the ORDERS table in ONE MySQL query.
This is a query you should be using
select distinct u.* from users u
inner join orders o on o.user_id = u.id;
Note the distinct and u.*. This query will not select fields from orders and it will not select the same user twice (if one has more than one order).
Demo: http://sqlfiddle.com/#!2/6ebcc/3
You can use mysql join syntax. Assuming both of your tables has userid column, this is the example :
SELECT * FROM USERS a JOIN ORDERS b ON
a.UserId = b.UserId
This is a simple database operation, see here for the explanation join
I have two tables in a MySQL Database.
Users table and Users Meta Table
I am looking for a way to get all the information out of both tables with one query. But without repeating the information from Users table.
This is all information relating to the users id number as well. So for example user_id = 1.
Is there a way to query the database and collect all the information I from both tables without repeating the information from the first?
Structure Example
Users Table
user_id
user_login
user_pass
Users Meta Table
user_meta_id
user_id
user_meta_key
user_meta_value
Im wanting to get out of this
user_id, user_login, user_pass, user_meta_id, user_id, user_meta_key, user_meta_value
user_meta_id, user_id, user_meta_key, user_meta_value
user_meta_id, user_id, user_meta_key, user_meta_value
Sure, that's easy, just specify the fields you want from each table in the query with a join and don't include the columms that are repeated.
SELECT Users.field1, Users.field2, Users.field3, Users.user_ID,
UsersMeta.field4, UsersMeta.field5
FROM USERS
LEFT JOIN UsersMeta ON (Usuers.user_ID=UsersMeta.User_ID)
SELECT DISTINCT table1.id, table1.field2, table1.field3, tab_id.id_table1
FROM table1
LEFT JOIN tab_id ON (table1.id=tab_id.id_table1)
yes, it is possible using DISTINCT keyword in query
SELECT DISTINCT Users.field1, DISTINCT users.field2, UsersMeta.field3
FROM USERS, UsersMeta
WHERE Users.user_ID=UsersMeta.User_ID
Distinct description
You didn't mention what database server you are using.
Assuming your tables are like:
USERS (user_id, first_name, last_name, gender)
USER_META (user_id, comment_count, likes)
Your query would look like this in MySQL:
SELECT u.user_id, first_name, last_name, gender, comment_count, likes
FROM USERS u LEFT JOIN USER_META m ON (u.user_id = m.user_id);
That's the work of front-end tools/language, e.g. Crystal Report, PHP, C#, etc. Don't do it in query