Garethp Posted August 8, 2010 Share Posted August 8, 2010 I want to make a search where I have multiple WHERE clauses that are optional. I tried OR, but it doesn't give me what I want. Here's what I have "SELECT members.ID, members.Username, COUNT(series.ID) as Stories FROM members, series WHERE members.Username LIKE '$Input%' AND (series.Author=members.ID OR series.CoAuthor LIKE concat('%;' + members.ID + ';%')) LIMIT $Start, $Limit" The problem is that this excludes members who haven't Authored a series. I want to search ALL members, even if they haven't included a series, but also to fetch the series that they HAVE Authored, IF they have. I want to make it one SQL query so that I can ORDER BY COUNT(series.ID) or by another list of columns which I plan to add later When I tried changing the AND to OR, it gave me the username of anyone who had written a story (I think), but what I want is to fetch series, if and only if they have Authored a series How can I do this? Quote Link to comment https://forums.phpfreaks.com/topic/210119-make-an-optional-clause/ Share on other sites More sharing options...
Garethp Posted August 8, 2010 Author Share Posted August 8, 2010 Also, a second problem, I've found that adding COUNT(series.ID) only allows returns 1 result. Even though 4 people have Authored stories, only 1 row returns results Quote Link to comment https://forums.phpfreaks.com/topic/210119-make-an-optional-clause/#findComment-1096572 Share on other sites More sharing options...
Garethp Posted August 8, 2010 Author Share Posted August 8, 2010 I was thinking of doing something like this, would it work? SELECT DISTINCT(members.ID) as ID, members.Username as Username FROM members, series WHERE members.Username LIKE '$Input%' IF COUNT((series.Author=members.ID OR series.CoAuthor LIKE CONCAT ('%;', members.ID, ';%')) THEN AND (series.Author=members.ID OR series.CoAuthor LIKE CONCAT('%;',members.ID,';%')) LIMIT 0, 15 Would that work, and if so, how would I do it? Quote Link to comment https://forums.phpfreaks.com/topic/210119-make-an-optional-clause/#findComment-1096658 Share on other sites More sharing options...
fenway Posted August 9, 2010 Share Posted August 9, 2010 So many things. First, you need a left join if you want to find non-matching rows. Second, a count(*) without a group by will always return just one row. Third, DISTINCT is not a function. Quote Link to comment https://forums.phpfreaks.com/topic/210119-make-an-optional-clause/#findComment-1097257 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.