SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Apr 2013
    Posts
    104
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Optimize Sql query (Mysql )

    Hi,

    I have following 4 sql queries .

    I want to join all these 4 queries into 1 query and get the result.

    SELECT COUNT(*) AS table1_count FROM table1 WHERE active=1

    SELECT COUNT(*) AS table2_count FROM table2 WHERE active=0

    SELECT COUNT(*) AS table3_count FROM table3 WHERE active=1

    SELECT COUNT(*) AS table4_count FROM table4 WHERE active=1

    Any idea?

    -Thanks

  2. #2
    From space with love silver trophy
    SpacePhoenix's Avatar
    Join Date
    May 2007
    Location
    Poole, UK
    Posts
    5,077
    Mentioned
    103 Post(s)
    Tagged
    0 Thread(s)
    What is the table structure for each table (eg for fields to join on for example in a forum an id field in a users table and a poster_id in a posts table would be used for a join)?
    Community Team Advisor
    Forum Guidelines: Posting FAQ Signatures FAQ Self Promotion FAQ
    Help the Mods: What's Fluff? Report Fluff/Spam to a Moderator

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,341
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by edge82 View Post
    I want to join all these 4 queries into 1 query and get the result.
    Code:
    SELECT 'table1' AS the_table
         , COUNT(*) AS the_count 
      FROM table1 
     WHERE active=1
    UNION ALL
    SELECT 'table2' 
         , COUNT(*)
      FROM table2 
     WHERE active=0
    UNION ALL
    SELECT 'table3' 
         , COUNT(*)
      FROM table3 
     WHERE active=1
    UNION ALL
    SELECT 'table4' 
         , COUNT(*) 
      FROM table4 
     WHERE active=1
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Zealot
    Join Date
    Apr 2013
    Posts
    104
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks r937 and SpacePhoenix

    It works.



Tags for this Thread

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
  •