Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何使用唯一键选择包含非唯一键的行?_Mysql - Fatal编程技术网

Mysql 如何使用唯一键选择包含非唯一键的行?

Mysql 如何使用唯一键选择包含非唯一键的行?,mysql,Mysql,我有下面的MySQL表 ---------------------------- | id | pid | operation | ---------------------------- | 5 | 12 | pending | | 7 | 19 | sent | | 8 | 12 | replaced | | 9 | 16 | sent | | 12 | 12 | closed | | 14 |

我有下面的MySQL表

----------------------------
| id |   pid   | operation |
----------------------------
| 5  |   12    |  pending  |
| 7  |   19    |  sent     |
| 8  |   12    |  replaced |
| 9  |   16    |  sent     |
| 12 |   12    |  closed   |
| 14 |   21    |  sent     |
----------------------------
id
是唯一的操作id,而
pid
是产品id,表示为哪个产品执行哪个操作,因此不是唯一的。我需要列出产品的所有操作,仅使用操作id

我可以通过使用子选择这样做

SELECT * FROM operations WHERE pid = (SELECT pid FROM operations WHERE id = 8);
这个查询列出了我需要的确切结果,如

----------------------------
| id |   pid   | operation |
----------------------------
| 5  |   12    |  pending  |
| 8  |   12    |  replaced |
| 12 |   12    |  closed   |
----------------------------

问题是,;如果没有子选择,我如何执行此操作?

您可以像这样使用join

SELECT a.* FROM operations a
join operations b on a.pid =b.pild
WHERE b.id=8
使用
加入

SELECT o1.* 
FROM operations o1 join
     operations o2 on o1.pid=o2.pid
WHERE o2.id = 8
结果:

id  pid operation
-------------------
5   12  pending
8   12  replaced
12  12  closed
样本结果