gpt4 book ai didi

mySql 在非唯一列上连接两个表

转载 作者:行者123 更新时间:2023-11-29 02:05:46 28 4
gpt4 key购买 nike

您好,有以下表格:

表区:

id   DD   text   
---|----|-----
1 | 01 | texas
2 | 02 | ny
5 | 03 | washington

session table :

id   DD   CC   text
---|----|----|-----
1 | 01 | 01 | text1
2 | 02 | 01 | text2
5 | 02 | 02 | text3
3 | 02 | 03 | text4
4 | 03 | 01 | text5
5 | 03 | 02 | text6
6 | 01 | 02 | text7

table 上人:

id   name    DD   CC
---|-------|----|----
1 | john | 02 | 03
2 | mike | 03 | 02
3 | julia | 01 | 02

我想进行查询,以便得到以下结果:

结果:

 name     District    Council
-------|------------|-------
john | ny | text4
mike | washington | text6
julia | texas | text7

到目前为止,我有以下查询:

select p.name,d.text as district,c.text as council
from person p
inner join districts d on p.DD=d.DD
inner join councils c on p.DD=c.DD and p.CC=c.CC
where 1;

我认为逻辑应该是正确的,但不知何故我遇到了错误...任何人都可以帮助理解这一点或指出正确的方向吗?

如果我这样做,它会返回结果,但不是预期的结果:

select p.name,d.text as district,c.text as council
from person p
inner join districts d on p.DD=d.DD
inner join councils c on p.CC=c.id
where 1;

谢谢

编辑:这是一个整理问题...如果您发现这是我的建议是不要使用查询浏览器,因为错误不是很详细...它可能有一个选项,但我不知道!

谢谢大家

最佳答案

我不知道您的架构,但这是我所做的(而且效果很好!)

CREATE TABLE `districts` (
`id` INT(10) unsigned NOT NULL,
`DD` CHAR(20) NOT NULL,
`text` CHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `councils` (
`id` INT(10) unsigned NOT NULL,
`DD` CHAR(20) NOT NULL,
`CC` CHAR(20) NOT NULL,
`text` CHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `person` (
`id` INT(10) unsigned NOT NULL,
`DD` CHAR(20) NOT NULL,
`CC` CHAR(20) NOT NULL,
`name` CHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO districts (`id`, `DD`, `text`) VALUES ('1','01','texas');
INSERT INTO districts (`id`, `DD`, `text`) VALUES ('2','02','ny');
INSERT INTO districts (`id`, `DD`, `text`) VALUES ('5','03','washington');

INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('1','01','01','text1');
INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('2','02','01','text2');
INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('3','02','03','text4');
INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('4','03','01','text5');
INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('5','03','02','text6');
INSERT INTO councils (`id`, `DD`, `CC`, `text`) VALUES ('6','01','02','text7');

INSERT INTO person (`id`, `name`, `DD`, `CC`) VALUES ('1','john','02','03');
INSERT INTO person (`id`, `name`, `DD`, `CC`) VALUES ('2','mike','03','02');
INSERT INTO person (`id`, `name`, `DD`, `CC`) VALUES ('3','julia','01','02');

SELECT p.name, d.text AS district, c.text AS council
FROM person p
INNER JOIN districts d ON p.DD = d.DD
INNER JOIN councils c ON p.DD = c.DD
AND p.CC = c.CC
WHERE 1

关于mySql 在非唯一列上连接两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com