SQL 连接内部或外部
我有两张桌子: 用户:id 用户名 部落 部落: id clan crest
我尝试按用户名进行搜索,并输出用户名的部落。
查询:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest` FROM `users` JOIN `clans` ON `users`.`username` LIKE '%gu%'
输出:
id username clan crest
2 gusar 26_760.gif
3 gusar11 Tong 26_760.gif
如果部落为空,波峰将为空..但是...(
我想要以下结果:
id username clan crest
2 gusar
3 gusar11 Tong 26_760.gif
I have two tables:
users: id username clan
clans: id clan crest
I trying to do the search by username with output the clan of username.
Query:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest` FROM `users` JOIN `clans` ON `users`.`username` LIKE '%gu%'
Output:
id username clan crest
2 gusar 26_760.gif
3 gusar11 Tong 26_760.gif
If clan is empty crest will be empty.. But ... (
I want following result:
id username clan crest
2 gusar
3 gusar11 Tong 26_760.gif
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您使用 LIKE 从一张表连接到另一张表,通常没有什么理由这样做。相反,您可能希望在 WHERE 子句中使用它,并且应该使用外键在表之间进行连接。
您想要使用 LEFT OUTER JOIN(或简称 LEFT JOIN)来尝试匹配第二个表中的所有行,但如果没有匹配则显示 NULL 值:
请注意,在 users 表中,理想情况下您应该保留部落 ID,而不是部落头衔。然后,您可以使用此查询来执行搜索:
You're joining from one table to another using a LIKE, typically there is little reason why you would do this. Instead you likely want that in a WHERE clause, and you should be joining between the table using a foreign key.
You want to use a LEFT OUTER JOIN (or LEFT JOIN for short) to attempt to match all of the rows in the second table, but to show NULL values if there was no match:
Mind you, in your users table, ideally you should hold the clan id and not the clan title. You would then use this query to perform your search:
如果您想要第一个表的结果,即使第二个表中没有匹配项,您也需要使用 LEFT OUTER JOIN。
If you want results from the first table, even when there are NO matches in the second table, you want to use a LEFT OUTER JOIN.
尝试
Try
您需要使用某些条件连接表。您正在使用 ON,而您应该使用 WHERE。我假设
users
.clan
与clans
.clans
相关?试试这个:You need to join the table using some condition. You're using an ON where you should use a WHERE. I assume
users
.clan
relates toclans
.clans
? Try this: