Ken2k7 Posted August 29, 2008 Share Posted August 29, 2008 Hey, Having these 2 database table structures: CREATE TABLE IF NOT EXISTS `user` ( `id` int( NOT NULL AUTO_INCREMENT `name` varchar(20) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS `cars` ( `id` int( NOT NULL AUTO_INCREMENT `user_id` int( NOT NULL, PRIMARY KEY (`id`) ); What I want to do is select all `user` who has less than 3 `cars` (or in this case, less than 3 columns in the `cars` table). Can someone help me with this query? Thanks! Link to comment https://forums.phpfreaks.com/topic/121907-solved-mysql-count/ Share on other sites More sharing options...
fenway Posted August 29, 2008 Share Posted August 29, 2008 select user_id, count(*) as cnt from cars group by user_id having cnt < 3 Link to comment https://forums.phpfreaks.com/topic/121907-solved-mysql-count/#findComment-629040 Share on other sites More sharing options...
Ken2k7 Posted August 29, 2008 Author Share Posted August 29, 2008 Thanks, is this right: <?php $sql = "SELECT `cars`.user_id, COUNT(*) as cnt FROM `user`, `cars` GROUP BY `cars`.user_id HAVING `user`.name = 'ken' AND `cnt` < '3' "; ?> Link to comment https://forums.phpfreaks.com/topic/121907-solved-mysql-count/#findComment-629071 Share on other sites More sharing options...
fenway Posted August 29, 2008 Share Posted August 29, 2008 Not exactly... no join condition! Try: select c.user_id, count(*) as cnt from cars as c inner join user as u on ( u.id = c.user_id ) group by c.user_id having cnt < 3 Link to comment https://forums.phpfreaks.com/topic/121907-solved-mysql-count/#findComment-629130 Share on other sites More sharing options...
Ken2k7 Posted August 30, 2008 Author Share Posted August 30, 2008 Thanks Link to comment https://forums.phpfreaks.com/topic/121907-solved-mysql-count/#findComment-629370 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.