If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Tricky SELECT Statement

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-29-10, 01:48
sjarman sjarman is offline
Registered User
 
Join Date: Jan 2010
Posts: 9
Tricky SELECT Statement

I'm just hoping that someone might be able to help me out with a tricky SELECT statement that I can't get my head around.

I have two tables - one that contains SERVER items, and another that contains performance ALERTS for those servers.

Here are some relevant fields:

SERVERS (table)
serverid
accountid
servername

ALERTS (table)
alertid
serverid
alerttext

I need to write a SELECT statement that gives me all of the servers for a particular account. e.g.

SELECT serverid, servername FROM servers WHERE accountid=123

and also a COUNT of the number of alerts that each server currently has.

So, the end result might look something like this:

serverid servername numalerts
0 svr01 0
1 svr02 3
2 svr03 1
3 svr04 0

Can anyone help out with that?
Reply With Quote
  #2 (permalink)  
Old 01-29-10, 07:13
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
this is not tricky at all
Code:
SELECT servers.serverid
     , servers.servername 
     , COUNT(alerts.serverid) AS numalerts
  FROM servers 
LEFT OUTER
  JOIN alerts
    ON alerts.serverid = servers.serverid
 WHERE servers.accountid = 123
GROUP
    BY servers.serverid
your basic left outer join count query

__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 01-29-10, 07:24
sjarman sjarman is offline
Registered User
 
Join Date: Jan 2010
Posts: 9
You're a life-saver. Been struggling with that for hours! Thanks so much for the help.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On