我的問題如下圖所述,資料庫結構及資料在下面程式碼區塊,求大牛幫忙看看..
我希望得到的結果是:
表結構及資料如下
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 ;
有沒有大牛能提供一個更有效率的寫法呢?
天蓬老师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
如果是上面的資料的話,這條sql應該就滿足了。 。 。在不滿足,就不管了......
這是我的查詢結果
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 ;
效率有問題..