sploit Posted February 10, 2006 Share Posted February 10, 2006 I have a table like this:col1 | col2----------------1 | A1 | B2 | A3 | A3 | B3 | CI want to select all col1 where col2 is equal to A and B i.e. the result will be col1=1 and 3I'm stumped. Can someone help me with the query? Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/ Share on other sites More sharing options...
shai1 Posted February 10, 2006 Share Posted February 10, 2006 Is this what you are after?select col1 where col2='A' and col2='B'; Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/#findComment-11562 Share on other sites More sharing options...
fenway Posted February 10, 2006 Share Posted February 10, 2006 There are a number of ways to do this; the easiest, IMHO, is the following (UNTESTED):[code]SELECT col1, COUNT(col2) AS cnt FROM yourTable WHERE col2 IN ('A','B') GROUP BY col1 HAVING cnt = 2[/code]That is, count the number of answers for each col1 value, query only for A or B, and see where only 2 answers are returned (i.e. A and B). Hope that helps. Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/#findComment-11565 Share on other sites More sharing options...
wickning1 Posted February 11, 2006 Share Posted February 11, 2006 [code]SELECT col1, GROUP_CONCAT(col2 SEPARATOR '|') AS con FROM table GROUP BY col1 HAVING con LIKE 'A' AND con LIKE 'B'[/code]lol I didn't test that and it'll be slow as hell on a big table (>100000 rows) but it might work for you.If you know you're always going to be selecting only 2 values for col2 then you can do a join faster:[code]SELECT t1.col1 FROM table t1, table t2 WHERE t1.col1=t2.col1 AND t1.col2='A' AND t2.col2='B'[/code]You can do a 3-table join for 3 values, etc, but it will be hard to adjust the query dynamically. Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/#findComment-11584 Share on other sites More sharing options...
wickning1 Posted February 11, 2006 Share Posted February 11, 2006 That is brilliant. I gave him 2 other solutions in the PHP Help forum, but that one beats them both. Very nice. Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/#findComment-11586 Share on other sites More sharing options...
shoz Posted February 11, 2006 Share Posted February 11, 2006 Sploit. It's against the [a href=\"http://www.phpfreaks.com/forums/index.php?act=boardrules\" target=\"_blank\"]Board Guidelines[/a] to post multiple topics on the same issue.I've merged the topics and deleted a few posts that make the thread confusing after the merge. Keep that in mind when reading.Read through the board guidelines before your next post. Link to comment https://forums.phpfreaks.com/topic/3383-select-statement/#findComment-11593 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.