我有两个:
壁炉表:table1
id | text
-------------
1 t1
2 t2
...
第二张表:table2
id | idTable1 | text2
-------------------------------
1 1 text1Table2
2 1 text2Table2
3 1 text3Table2
4 2 text4Table2
5 2 text5Table2
...
如果我做左加入:
SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.idTable1
结果是这样的:
id | text | id | idTable1 | text2
------------------------------------------
1 t1 1 1 text1Table2
1 t1 2 1 text2Table2
1 t1 3 1 text3Table2
2 t2 4 2 text4Table2
2 t2 5 2 text5Table2
...
但是我希望在第一个表中重复的行仅显示一次,如下所示:
id | text | id | idTable1 | text2
------------------------------------------
1 t1 1 1 text1Table2
1 - 2 1 text2Table2
1 - 3 1 text3Table2
2 t2 4 2 text4Table2
2 - 5 2 text5Table2
...
编辑:并将此结果添加到mysql视图中
您可以使用case语句和子查询来确定给定行是否为第一行(即最低的行table2.id
)table2.idTable
CREATE VIEW myView AS SELECT
t1.id id1,
(CASE
WHEN t2.idTable1 IS NULL OR NOT EXISTS (
SELECT 1
FROM table2 t3
WHERE t3.idTable1 = t2.idTable1
AND t3.id < t2.id
) THEN t1.text ELSE '-'
END) text1,
t2.id id2,
t2.idTable1,
t2.text2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.idTable1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句