用于命名3个id标签的SQL语句

时间:2015-04-23 12:11:50

标签: mysql sql

我试图得到我的查询3标签名称而不是获取tag_id。情况就是这样:

create table names (
 ˋattr_idˋ int(11) unsigned not null auto_increment,
 ˋattr_nameˋ varchar(30),
 primary key(ˋattr_idˋ)
) engine=MyISAM

create table posts (
 ˋpost_idˋ int(5) unsigned not null auto_increment
 ˋattr_1 int(11) unsigned,
 ˋattr_2ˋ int(11) unsigned,
 ˋattr_3ˋ int(11) unsigned,
 ˋreferencedˋ int(5),
 primary key (ˋpost_idˋ)
) engine=MyISAM

insert into names (ˋattr_nameˋ) values 
(''),('name1'),('name2'),('name3'),('name4'),('name5'),('name6');

insert into posts (ˋattr_1ˋ, ˋattr_2ˋ, ˋattr_3ˋ, referenced) values
(1, 2, 3, null), (1, 4, 2, 1), (1, 3, 1, 2), (1, 2, 5, 1), (4, 2, 5, 1)

我想要获得的结果是referenced值等于post_id = 1的行,对于所有这些行,请更改其attr_1attr_2和对于attr_3表中的attr_namenames

这就是我在提出问题之前尝试过的。在这里,我可以获得referenced值等于1的帖子:

SELECT post_id, attr_1, attr_2, attr_3, referenced
FROM posts
WHERE a.referenced = 1;

但是在这里,尝试更改nameattr_1attr_2的{​​{1}}内容无法获得我想要的内容:

attr_3

有人可以帮我这个吗?

感谢您的建议。

3 个答案:

答案 0 :(得分:1)

您需要左连接才能获取每个值的名称:

SELECT post_id,
       att1.attr_name,
       att2.attr_name,
       att3.attr_name,
       referenced
FROM   posts a
       LEFT JOIN names att1
              ON a.attr_1 = att1.attr_id
       LEFT JOIN names att2
              ON a.attr_2 = att2.attr_id
       LEFT JOIN names att3
              ON a.attr_3 = att3.attr_id
WHERE  a.referenced = 1; 

左连接将防止忽略不匹配的行(如果存在)。

答案 1 :(得分:1)

一个非常有效的解决方案是为每个attr_加入一次名称表,如下所示:

SELECT p.post_id, n1.attr_name, n2.attr_name, n3.attr_name, p.referenced
FROM posts p
LEFT JOIN names n1 ON p.attr_1 = n1.attr_id
LEFT JOIN names n2 ON p.attr_2 = n2.attr_id
LEFT JOIN names n3 ON p.attr_3 = n3.attr_id
WHERE p.referenced = 1 

根据您的样本数据,输出将为:

post_id attr_name       attr_name       attr_name   referenced
2                       name3           name1           1
4                       name1           name4           1
5       name3           name1           name4           1

答案 2 :(得分:0)

你应该为每个attr值进行3次连接:

SELECT a.post_id, b1.attr_name, b2.attr_name, b3.attr_name, a.referenced
FROM posts a, names b1, names b2, names b3
WHERE a.referenced = 1 AND
      a.attr_1 = b1.attr_id AND
      a.attr_2 = b2.attr_id AND
      a.attr_3 = b3.attr_id
GROUP BY a.post_id