gpt4 book ai didi

mysql - 如何在 Sql View 查询中引用值

转载 作者:行者123 更新时间:2023-11-29 20:47:09 25 4
gpt4 key购买 nike

--
-- 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钢铁侠马克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|
+--------+----------+--------+

最佳答案

只需 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

关于mysql - 如何在 Sql View 查询中引用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38366399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com