简体   繁体   中英

Getting a query result whiting a group by

I'm trying to get some result of a query. The table stock information about which page in a website visited by a user. So I can have in a row user that visit page "A" per example and a second row with the same user who visit the page "B". I want to do a query that select the user or users who visit the page "A" and "B". I can't make a “and” in my where condition because there are just one column.

There is the table structure

ID | user_id | page | views
1      1        A        44
2      1        B       120
3      2        A       140
4      3        A        22

I have try this but doesn't work

SELECT users.name,users.id,users.email
                        FROM users
                        JOIN help_messages ON users.id = help_messages.id_user
                        WHERE (PAGE LIKE  '%clubs%' or PAGE like '%profile%') and views >= 1
                        GROUP BY help_messages.id_user, help_messages.page

So any solutions please. Thanks

A general approach to this uses aggregation and a having clause:

select user_id
from table t
group by user_id
having sum(page = 'A') > 0 and sum(page = 'B') > 0;

The first condition in the having clause counts the number of rows that have an 'A' and only allows user_id s that have at least one such row. The second condition does the same for 'B' .

This is a general approach because it is easy to add additional pages. Also, if you want someone who visited 'A' but not 'B', you would just use:

having sum(page = 'A') > 0 and sum(page = 'B') = 0;

See if this works for you:

SELECT sub1.* FROM
(SELECT * FROM users WHERE page = 'A') AS sub1
JOIN
((SELECT * FROM users WHERE page = 'B') AS sub2
ON (sub1.user_id = sub2.user_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM