我有三张桌子
1)cd_register
|----------------------------------------------------|
| username | name | age | sex | dob |
|----------------------------------------------------|
2)cd_social
|-------------------------------------|
| username | religion | caste |
|-------------------------------------|
和 3)cd_professional
|----------------------------------------|
| username | occupation | education |
|----------------------------------------|
现在我在mysql中使用此查询但是它给出了错误
SELECT cd_register.name, cd_register.age, cd_register.dob, cd_social.religion, cd_social.caste, cd_professional.profession
FROM cd_register, cd_social,cd_professional
WHERE
cd_register.sex = 'Male',
cd_social.religion = 'Hindu',
cd_social.caste = 'Brahmin',
cd_professional.occupation = 'Doctor',
cd_register.username = cd_social.username AND
cd_register.username = cd_professional.username
现在我想提一下username
是所有表格的primary key
。也
username
cd_register
foreign key
cd_social
username
。也
cd_register
foreign key
cd_professional
{{1}} {{1}}。{/ 1}。{/ 1}}
答案 0 :(得分:9)
您可以使用join
SELECT t1.name, t1.age, t1.dob, t2.religion, t2.caste, t3.profession
FROM cd_register as t1
LEFT JOIN cd_social as t2
ON t1.username = t2.username and t2.caste = 'Brahmin' and t2.religion ='Hindu'
LEFT JOIN cd_professional as t3
ON t1.username = t3.username and t3.occupation = 'Doctor'
WHERE t1.sex = 'Male'
答案 1 :(得分:1)
你的WHERE
子句中有逗号,这肯定会导致错误(你可能想要AND
)尝试这个:
SELECT cdr.name, cdr.age, cdr.dob, cds.religion, cds.caste, cdp.profession
FROM cd_register cdr
JOIN cd_social cds
ON cdr.username = cds.username
JOIN cd_professional cdp
ON cdr.username = cdp.username
WHERE cdr.sex = 'Male'
AND cds.religion = 'Hindu'
AND cds.caste = 'Brahmin'
AND cdp.occupation = 'Doctor'
答案 2 :(得分:0)
告诉我们错误是什么可能会有所帮助。
此外,最后两行是相同的。
你可能也需要加入cd_professional表。