请教Mysql同表和多表一起关联查询的问题,谢谢

各位老师好,请教下,同表和多表一起联合查询。这是一个宠物项目的表。

同一个有关联,不同的表也有关联,请问如何联合查询
表table_cat

表table_type

表table_color

问题:希望调出table_cat表中id=1的name,father,mother,type,color所对应的实际值,导出到数组中。

也就是结果应该是:
name=>cat01,
father=>cat02,
mother=>cat03,
type=>类型1,
color=>黑

主要是table_cat中,father是指向同表内id=2的值,mother是指向同表内id=3的值。

因为,我是使用TP6开发,所以就不写出我的测试语句了,关键都不成功。我想知道原始的SQL执行语句正确的是什么,然后我在自己研究TP6下如何套用。先谢过了!

最佳答案

以下是查询整个列表的语句 SELECT c.id, c.name, cf.name as father, cm.name as mother, t.type, co.color FROM cat AS c left join cat as cf on c.father = cf.id left join cat as cm on c.mother = cm.id LEFT JOIN type as t on c.type = t.id LEFT JOIN color as co on c.color = co.id order by c.id

2年前 评论
bpdama (楼主) 2年前
bpdama (楼主) 2年前
讨论数量: 10

查询color和type这个我都会,就是不知道同一个表内如何操作。另外,就是是不是我从根本上就逻辑错误了,就不应该这样设计。

2年前 评论
SELECT name,father,mother,table_type.type,table_color.color
FROM table_cat,table_type,table_color
WHERE table_cat.type = table_type.id
AND  table_cat.color = table_color.id
AND  table_cat.id = 1


SELECT name,father,mother,table_type.type,table_color.color
FROM table_cat 
LEFT JOIN table_type ON table_cat.type = table_type.id
LEFT JOIN table_color ON table_cat.color = table_color.id
WHERE  table_cat.id = 1

这两种方式查询都可以

2年前 评论
小李世界 2年前

不应该有个father_id ,mother_id 字段嘛,table_cat 表 也太乱了

2年前 评论

先真心谢谢你们的回复,表应该是不乱的,这是个最基本的简单表,关联其他2个表,我都会,没有问题。就是同表有问题,就算有father_id也没用。问了一些朋友,都没同表查询过。可能我这个思路不对。

2年前 评论

但是写出来,不排除有大神存在,或者的确是我自己对数据库理解不透彻。

SELECT c.name,c.father,c.mother,t.type,co.color FROM table_type t LEFT JOIN table_cat c ON t.id=c.type LEFT JOIN table_color co ON co.id=c.color WHERE c.id=1;

我用这个是完全可以关联到另外2个表的。跟你的语句其实一样。

SELECT c.name,c.father FROM table_cat c LEFT JOIN table_cat a ON a.father=c.uid WHERE c.id=1;

然后,我用这个语句想查询出father的值,就是不行,只能显示2,无法显示cat02。

2年前 评论

以下是查询整个列表的语句 SELECT c.id, c.name, cf.name as father, cm.name as mother, t.type, co.color FROM cat AS c left join cat as cf on c.father = cf.id left join cat as cm on c.mother = cm.id LEFT JOIN type as t on c.type = t.id LEFT JOIN color as co on c.color = co.id order by c.id

2年前 评论
bpdama (楼主) 2年前
bpdama (楼主) 2年前

设计表你还是先从字段上规范做起吧。

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!