我如何获得所需的结果?

时间:2014-07-11 11:21:33

标签: mysql

需要有关mysql语句的帮助

P_ID |  P_NAME 

1   P1
2   P2



PT_ID | P_ID | S_ID
1   1   1
1   1   2
1   1   3
1   2   1
1   2   2
1   2   3
1   2   4

必填结果:

P_ID | P_NAME | S_ID    
1   P1  3
2   P2  4

4 个答案:

答案 0 :(得分:1)

Select t1.P_ID, t1.P_Name, count(t2.SID) as S_ID
     FROM table1 t1 join table t2 on t1.P_ID = t2.P_ID
          Group by t2.P_ID 

答案 1 :(得分:0)

这应该有效:

SELECT tab1.P_ID,
       P_NAME,
       S_ID
  FROM tab1 
  JOIN tab2
    ON tab1.p_id = tab2.p_id;

答案 2 :(得分:0)

也许是这样的:

SELECT
    Table1.P_ID,
    Table1.P_NAME,
    MAX(Table2.S_ID) AS S_ID
FROM
    Table1
    JOIN Table2 ON Table1.P_ID=Table2.P_ID
GROUP BY
    Table1.P_ID,
    Table1.P_NAME 

答案 3 :(得分:0)

尝试使用INNER JOIN

SELECT T1.P_ID, T1.P_NAME, MAX(T2.S_ID) AS S_ID
FROM Table1 T1
INNER JOIN Table2 T2 ON T1.P_ID=T2.P_ID
GROUP BY T1.P_ID, T1.P_NAME