Results 1 to 3 of 3

Thread: SQL SubQuery Condition

  1. #1
    Join Date
    Oct 2005
    Location
    Seattle, WA
    Beans
    494
    Distro
    Ubuntu 12.04 Precise Pangolin

    SQL SubQuery Condition

    SQL Wizards, I need your help!

    I'm trying to put together a rather complex query using some obfuscated crazy framework... details aside, I'd like to do something like the following:

    SELECT A.ATT_1, A.ATT_2, (SELECT COUNT(*) FROM TABLE_B) AS B_COUNT, A.ATT_3 FROM TABLE_A A WHERE B_COUNT = '2';

    I keep getting an error that B_COUNT doesn't exist. Is there a way I can write conditions on the sub-query returned? Thanks so much in advanced!

    www.runtime-era.com - Blog About My Journey as a Developer

  2. #2
    Join Date
    Dec 2011
    Beans
    1

    Re: SQL SubQuery Condition

    I believe you get the error because you have to join the tables in order to use the column from table B in your where clause, I'm not entirely sure though. I think I've had very similar queries in some of my projects, and I've almost always had to do a INNER or LEFT JOIN.

  3. #3
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: SQL SubQuery Condition

    I believe m0zilla is correct, specifically something like this:

    Code:
    select a.att1, a.att2, a.att3, count(*)
    from table_a a
    inner join table_b b
    on a.<primary_key> = b.<foreign_key>
    group by a.att1, a.att2, a.att3
    having count(*) = 2
    The <primary_key> and <foreign_key> columns are up to you to designate. It's not clear from your post what these columns are in table_a and table_b.

    http://www.w3schools.com/sql/sql_having.asp

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •