我必须在三个表中使用mysql执行查询。
interface
---------------------
|id | name |
---------------------
|1 | inter1 |
---------------------
|2 | inter2 |
---------------------
inetrapp
--------------------------------------
|id | interid | appid |
--------------------------------------
|1 | 1 | 20 |
--------------------------------------
|2 | 1 | 21 |
--------------------------------------
|3 | 2 | 22 |
--------------------------------------
|4 | 2 | 23 |
--------------------------------------
app
--------------------------------------
id | appid | appname |
--------------------------------------
1 | 20 | sap |
--------------------------------------
2 | 21 | sap1 |
--------------------------------------
3 | 22 | wes |
--------------------------------------
4 | 23 | wes1 |
--------------------------------------
查询就像这样
select ti.id as id,
ti.name as name,
GROUP_CONCAT(DISTINCT tapp.appname order by ti.id SEPARATOR ",") as applications
from interface ti inner join interapp tiap on ti.id = tiap.interid inner join app as tapp on tiap.appid = tapp.appid where tapp.appname in ("sap1");
给出了以下结果
--------------------------------------
|id | name | applications |
--------------------------------------
|1 | inter1 | sap1 |
--------------------------------------
但我需要所有与inter1有关系的app,(即)我希望得到以下结果。
--------------------------------------
|id | name | applications |
--------------------------------------
|1 | inter1 | sap,sap1 |
--------------------------------------
请指导我修改上述查询。提前谢谢。
答案 0 :(得分:0)
SELECT a.id,
a.name,
GROUP_CONCAT(DISTINCT c.appname ORDER BY a.id SEPARATOR ',') result
FROM interface a
INNER JOIN inetrapp b
ON a.id = b.interid
INNER JOIN app c
ON b.appid = c.appid
INNER JOIN
(
SELECT DISTINCT a.interid
FROM inetrapp a
INNER JOIN app b
ON a.appid = b.appid
WHERE b.appname IN ('sap1')
) d ON a.id = d.interid
GROUP By a.id, a.name