如何在Sql View Query中引用一个值

时间:2016-07-14 05:50:33

标签: mysql sql variables output

--
-- Table structure for table `emp`
--

CREATE TABLE `emp` (
  `Emp_id` int(11) NOT NULL,
  `Name` varchar(30) DEFAULT NULL,
  `Sup_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `emp`
--

INSERT INTO `emp` (`Emp_id`, `Name`, `Sup_id`) VALUES
(1, 'Mark 18', NULL),
(2, 'Iron Man', 1),
(3, 'Hulk', NULL),
(4, 'Ant-Man', 2);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `emp`
--
ALTER TABLE `emp`
  ADD PRIMARY KEY (`Emp_id`),
  ADD KEY `Sup_id` (`Sup_id`);

--

这是我的桌子DESC

我希望输出为

像钢铁侠的情况一样 我喜欢这样的

2钢铁侠Mark 18

这意味着它要检查Emp_id和Dispaly对应的Emp _id名称

DESc结构

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Emp_id | int(11)     | NO   | PRI | NULL    |       |
| Name   | varchar(30) | YES  |     | NULL    |       |
| Sup_id | int(11)     | YES  | MUL | NULL    |       |
+--------+-------------+------+-----+---------+-------+

表内的值

+--------+----------+--------+
| Emp_id | Name     | Sup_id |
+--------+----------+--------+
|      1 | Mark 18  |   NULL |
|      2 | Iron Man |      1 |
|      3 | Hulk     |   NULL |
|      4 | Ant-Man  |      2 |
+--------+----------+--------+

我想要的输出格式

+--------+----------+--------+
| Emp_id | Name     | Sup_id |
+--------+----------+--------+
|      1 | Mark 18  |NULL    |
|      2 | Iron Man |MArk 18 |
|      3 | Hulk     |   NULL |
|      4 | Ant-Man  |Iron Man|
+--------+----------+--------+

1 个答案:

答案 0 :(得分:0)

只是LEFT JOIN表:

SELECT e.Emp_id, e.Name, es.Name AS Sup_name FROM emp AS e LEFT JOIN emp AS es ON e.Sup_id = es.Emp_id