Counting records from table that appear is one but not other: MYSQL

可紊 提交于 2019-12-11 05:46:17

问题


I have a two simple tables

users

+----+--------+-----------+
| id | gender | birthdate |
+----+--------+-----------+

userpreference

+----+------------------+-----------------+
| id | preference value | preference type |
+----+------------------+-----------------+

Question:

I want to query all people who have not listed a specific preference value such as 'shopping'.This includes all people who have not listed any preference types as well so that column could be null, however since userpreference's column 'id' references users as a foreign key, I also want to include in my count all people who don't show up in the second table (user preference)?

Total # of people who do not have preference value 'shopping' as their preference value:

Here is what i have tried:

SELECT
(
SELECT COUNT(DISTINCT userpreference.id) FROM userpreference
WHERE  preferencevalue != 'shopping')
+
(
SELECT COUNT(users.id)
FROM users
WHERE users.id NOT IN
(SELECT userpreference.Id
FROM userpreference )
)
AS'Total'

回答1:


Select Count(*)
From Users
Where Not Exists   (
                    Select 1
                    From UserPreference As UP1
                    Where UP1.id = Users.id
                        And UP1.PreferenceValue = 'Shopping'
                    )



回答2:


Try a RIGHT JOIN, that will include all people who dont show up in the second table

SELECT * FROM Users RIGHT JOIN Userpreference ON ( users.userID = Users.userID) WHERE preference_value = 'shopping'




回答3:


Try this:

SELECT COUNT(DISTINT U.id) FROM users U NATURAL LEFT JOIN userpreference UP WHERE UP.preferencevalue IS NULL OR UP.preferenceValue != 'shopping';

The LEFT JOIN should bring in all the users records whether or not they have a UP record.



来源:https://stackoverflow.com/questions/5188774/counting-records-from-table-that-appear-is-one-but-not-other-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!