如何连接mysql表
我有一个像这样的旧表:
user> id | name | address | comments
现在我必须创建一个“别名”表,以允许某些用户出于某种原因拥有别名。我创建了一个新表“user_alias”,如下所示:
user_alias> name | user
但现在由于我的 SQL 级别较差,我遇到了一个问题...如何连接两个表以生成类似这样的内容:
1 | my_name | my_address | my_comments
1 | my_alias | my_address | my_comments
2 | other_name | other_address | other_comments
我的意思是,我想做一个“SELECT.. .”查询以与“用户”表所有用户和所有别名相同的格式返回。像这样:
SELECT user.* FROM user LEFT JOIN user_alias ON `user`=`id`
但它对我不起作用..
I've an old table like this:
user> id | name | address | comments
And now I've to create an "alias" table to allow some users to have an alias name for some reasons. I've created a new table 'user_alias' like this:
user_alias> name | user
But now I have a problem due my poor SQL level... How to join both tables to generate something like this:
1 | my_name | my_address | my_comments
1 | my_alias | my_address | my_comments
2 | other_name | other_address | other_comments
I mean, I want to make a "SELECT..." query that returns in the same format as the "user" table ALL users and ALL alias.. Something like this:
SELECT user.* FROM user LEFT JOIN user_alias ON `user`=`id`
but it doesn't work for me..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先 - 您想要构建的查询并不简单,因为您正在尝试获取跨多个行的一些结果。因此,我将以应有的方式为您提供适当的解决方案(请阅读:以数据库开发人员会这样做的方式:-)。
首先,您应该修改
user_alias
表,使其包含id
列,但不包含名称。使用name
字段连接表并不是一个好主意。原因是可能有两个莎拉·康纳斯。然后,您可以使用以下查询从两个表中获取结果:
这样您将以如下格式获取结果:
在
user_alias
表中存在同一个人的两条或更多记录的情况下(等于id
's),你会得到这样的结果:First of all - the query you want to build is not trivial, because you are trying to get some results spanned across more than one row. So I will offer you a proper solution in a fashion like it should be (read: in a way a database developer will do this :-).
First, you should modify your
user_alias
table so that it will containid
column but not the name. It is not good idea to join your tables using thename
field. The reason for this is that there could be two Sarah Connors.Then, you can get results from both tables using this query:
This way you will get your results in such format:
In the situations when there are two or more records in
user_alias
table for the same person (equalid
's), you will get something like this:我认为你需要这样的东西:
你的原始查询在连接条件中不够具体。
I think you need something like this:
Your original query was not specific enough in the join condition.
类似的东西
会让你接近你想要的。
您需要将两个 SELECT 合并在一起,因为其他人提出的 LEFT JOIN 解决方案将仅在结果集中包含具有别名的用户的一行,而不是问题中指定的两行。
但是您应该将公共列连接到 user 并为 id 列(而不是 name 列)指定别名。
Something like
will get you close to what you want.
You need to UNION two SELECTs together because the LEFT JOIN solution proposed by others will include only one row in the result set for users with aliases, not two as specified in your question.
But you should make the common column joining user and alias the id column, not the name column.