Is it possible to do multiple SQL select statements within one query? Both select statements would be on the same table

join, sql

Solution

You should use a UNION statement.

SELECT hostname FROM mytable  
WHERE hostname  
    NOT LIKE '%obl%' AND 
    group NOT IN ('group1','group2','group3','group4','group5','group6','group7')  
    AND osname LIKE '%Windows%' 
    AND hostname not LIKE 'nic%'

UNION

SELECT hostname FROM mytable 
WHERE hostname 
    LIKE '%obl%' 
    AND group in ('group9','group0')

That will do it, but I think you could rethink those where conditions. I'll give it a thought and edit if necessary.

EDIT: You can achieve what you are trying to with a single query, no need for the union.

SELECT hostname FROM mytable 
WHERE (
    hostname NOT LIKE '%obl%' 
    AND group NOT IN ('group1','group2','group3','group4','group5','group6','group7') 
    AND osname LIKE '%Windows%' 
    AND hostname NOT LIKE 'nic%'
)
OR (
    hostname LIKE '%obl%' 
    AND group IN ('group9','group0')
)

Problem

This is probably due to my limited SQL knowledge, but I'm attempting to obtain data using a statement like this: ``` SELECT hostname FROM mytable WHERE hostname NOT LIKE '%obl%' AND group NOT IN ('group1','group2','group3','group4','group5','group6','group7') AND osname LIKE '%Windows%' AND hostname NOT LIKE 'nic%' ``` I realize that is probably a very bad statement, but it has worked so far. In the beginning I exclude entries where hostname isn't like "obl". I have another query like this: ``` SELECT hostname FROM mytable WHERE hostname LIKE '%obl%' AND group IN ('group9','group0') ``` From what I understand, joins wouldn't be used in this case, since both queries are on the same table (although my knowledge of joins is very limited). I'm accessing this database via a webservice, and I'm not certain what kind of database it is. Does anyone have any ideas of how I could get the values from both queries in one query?

Original source