SQL查询 - 获取两个表

时间:2016-11-15 06:54:34

标签: php mysql sql-server charts

表1(student_details)

拥有532个具有不同顾问的数据,每个数据都分配给一个顾问,如

    id advisor
    -- -------
    1  Bala
    2  Shanmugam
    3  Priya
    4 Bala
   etc..

表2中的Similaly:training_details

        id advisor
        -- -------
        1  Bala

       etc..

我尝试了这个查询,这将返回从table1单独分配给每个顾问的人数。我只想从两个表中计算并选择顾问

SELECT DISTINCT t1.advisor as advisor,IFNULL(COUNT(t2.advisor), 0) AS total  FROM advisor AS t1 
LEFT JOIN student_details AS t2 ON t1.advisor = t2.advisor AND t2.del!=1 GROUP BY t1.advisor;

类似地,我只想加入两个表条目,并在2列中返回相同计数的不同顾问;

1 个答案:

答案 0 :(得分:0)

SELECT advisor, COUNT(*) as TheCount
FROM
    (
     SELECT advisor FROM table 1
     UNION ALL
     SELECT advisor FROM table 2
     ) AS [TheNames]
GROUP BY advisor

SELECT x.advisor, COUNT(x.advisor)
    FROM (SELECT advisor
            FROM table1
          UNION ALL
          SELECT advisor
            FROM table2
         ) x
GROUP BY x.advisor