MySQL多行同一表

时间:2012-02-26 20:33:24

标签: mysql

我有一个包含配置数据行的MySQL表,即:

id  item   value1  value2
2   class   ship    bow
3   class   car     tires
5   reg     ship    level1
7   reg     ship    level2
9   reg     car     level5

我正在尝试创建一个选择item ='class'的所有行的查询,并返回一个与初始查询匹配的数据集+所有行,其中item ='reg'和value1 = value1(来自初始结果)。

因此,在这种情况下,结果集应如下所示:

class  ship  bow   reg   ship  level1
class  ship  bow   reg   ship  level2
class  car   tires reg   car   level5

我有点沮丧,希望这是有道理的。感谢您指出正确的方向!

2 个答案:

答案 0 :(得分:6)

你必须自己加入这个桌子。假设你的表名为configs(因为你没有告诉我们它叫什么),这样的东西应该有用:

select t1.item, t1.value1, t1.value2, t2.item, t2.value1, t2.value2
    from configs as t1
    inner join configs as t2
    on t2.value1 = t1.value1 and t2.item = 'reg'
    where t1.item = 'class';

如果您要求结果中也返回所有没有匹配reg行的行,请将inner join更改为left outer join。如果您希望此查询执行得体,请确保您在itemvalue1上有索引。

这是一个快速的概念证明,显示上面的查询有效:

mysql> create table configs (
    -> id int unsigned primary key auto_increment,
    -> item varchar(32) not null,
    -> value1 varchar(32) not null,
    -> value2 varchar(32) not null,
    -> index (item),
    -> index (value1)
    -> ) engine=innodb charset=utf8;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into configs (id, item, value1, value2) values
    -> (2, 'class', 'ship', 'bow'),
    -> (3, 'class', 'car', 'tires'),
    -> (5, 'reg', 'ship', 'level1'),
    -> (7, 'reg', 'ship', 'level2'),
    -> (9, 'reg', 'car', 'level5');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from configs;
+----+-------+--------+--------+
| id | item  | value1 | value2 |
+----+-------+--------+--------+
|  2 | class | ship   | bow    |
|  3 | class | car    | tires  |
|  5 | reg   | ship   | level1 |
|  7 | reg   | ship   | level2 |
|  9 | reg   | car    | level5 |
+----+-------+--------+--------+
5 rows in set (0.00 sec)

mysql> select t1.item, t1.value1, t1.value2, t2.item, t2.value1, t2.value2
    -> from configs as t1
    -> inner join configs as t2
    -> on t2.value1 = t1.value1 and t2.item = 'reg'
    -> where t1.item = 'class';
+-------+--------+--------+------+--------+--------+
| item  | value1 | value2 | item | value1 | value2 |
+-------+--------+--------+------+--------+--------+
| class | ship   | bow    | reg  | ship   | level1 |
| class | ship   | bow    | reg  | ship   | level2 |
| class | car    | tires  | reg  | car    | level5 |
+-------+--------+--------+------+--------+--------+
3 rows in set (0.00 sec)

答案 1 :(得分:0)

SELECT
  t1.*,
  t2.*
FROM
  table t1
  LEFT JOIN table t2 ON t2.item = 'reg' AND t2.value1 = t1.value1
WHERE
  t1.item = 'class'