Home  >  Q&A  >  body text

php - 请问这条多表联查的SQL怎么写?

我的问题如下图所述,数据库结构及数据在下面代码块,求大牛帮忙看看..

我希望得到的结果是:

表结构及数据如下

CREATE TABLE A(
id INT NOT NULL,
num INT NOT NULL
)CHARSET=utf8;

INSERT INTO A(id,num) VALUES(1,5),(2,7),(3,6);

CREATE TABLE B(
aid INT NOT NULL,
sid INT NOT NULL,
content VARCHAR(20) NOT NULL
)CHARSET=utf8;

INSERT INTO B(aid,sid,content) VALUES(3,1,'A'),(3,2,'B'),(3,3,'C');

CREATE TABLE C(
id INT NOT NULL,
time INT NOT NULL,
libs VARCHAR(20) NOT NULL
)CHARSET=utf8;

INSERT INTO C(id,time,libs) VALUES(2,18,'wagaga'),(3,16,'aaaa'),(1,15,'cc'),(3,17,'dddd'),(4,14,'eeee'),(3,10,'ffff'),(3,11,'bbbb');

这么可以满足我的需求,但是执行效率太低了...

select * from
(
SELECT distinct
    a.id,a.num,b.aid,b.sid,b.content,c.id as cid,c.time,c.libs
FROM
    a a
LEFT JOIN b b ON b.aid = a.id
LEFT JOIN c ON c.id = b.sid
WHERE a.id = 3
ORDER BY time DESC
) as TMP
GROUP BY cid ;

有没有大牛能提供一个更效率的写法呢?

阿神阿神2703 days ago767

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 13:09:35

    SELECT
        a.id,a.num,b.aid,b.sid,b.content,c.id,substring_index(group_concat(c.time order by c.time desc),',',1) ctime,substring_index(group_concat(c.libs order by c.time desc),',',1) clibs
    FROM a
    JOIN b ON b.aid = a.id
    JOIN c ON c.id = b.sid
    WHERE a.id = 3
    GROUP BY c.id ;

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-16 13:09:35

    SELECT
        *
    FROM
        a a
    LEFT JOIN b b ON b.aid = a.id
    LEFT JOIN c ON c.id = b.sid
    WHERE a.id = 3
    GROUP BY c.id

    If it is the above data, this sql should be satisfied. . . If you are not satisfied, just don’t care...


    This is my query result

    reply
    0
  • 高洛峰

    高洛峰2017-05-16 13:09:35

    select A.num,b.content,c.time,c.libs from A left join B on A.id=B.id left join C on C.id = A.id order by C.time desc limit 0,1

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:09:35

    What you want is not clearly described in the question. . .

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:09:35

    select * from
    (
    SELECT distinct
        a.id,a.num,b.aid,b.sid,b.content,c.id as cid,c.time,c.libs
    FROM
        a
    LEFT JOIN b  ON b.aid = a.id
    LEFT JOIN c ON c.id = b.sid
    WHERE a.id = 3
    ORDER BY time DESC
    ) as TMP
    GROUP BY cid ;
    

    There is a problem with efficiency..

    reply
    0
  • Cancelreply