SQL选择何时是不同的值

时间:2018-05-29 03:35:28

标签: php sql

我有两个表,我想从table_2中选择行,使用table_1中的行使用不同的值来显示一个没有雇用号码的注册投诉的表,我已经尝试过这个sql语句:

SELECT * FROM krita_db, sjofor_db WHERE employing_nr != nr ORDER BY id DESC

但如果

,则获取同一行的3
+----+--------------+-------------------------------------+
| id | employing_nr |              complaint              |
+----+--------------+-------------------------------------+
|  1 |          123 | something bad                       |
|  2 |          333 | you have to do something with this  |
+----+--------------+-------------------------------------+

+----+-----+------+---------+----------+
| id | nr  | navn | adresse |   tlf    |
+----+-----+------+---------+----------+
|  1 | 123 | ola  | ---     | 12345678 |
|  2 | 321 | kari | ---     | 98765432 |
|  3 | 222 | gerd | ---     | 12344321 |
+----+-----+------+---------+----------+ 

我只想展示一个相同的投诉,而不是3次,我该如何实现?

现在我的代码我得到了这张表:

+----+--------------+--------------------------------------+
| id | employing_nr |              complaint               |
+----+--------------+--------------------------------------+
|  1 |          123 | something bad                        |
|  1 |          123 | something bad                        |
|  2 |          333 | you have to do something with this   |
|  2 |          333 | you have to do something with this   |
|  2 |          333 | you have to do something with this   |
+----+--------------+--------------------------------------+

我想显示这个,带有未注册的employ_nr的投诉:

+----+--------------+--------------------------------------+
| id | employing_nr |              complaint               |
+----+--------------+--------------------------------------+
|  2 |          333 | you have to do something with this   |
+----+--------------+--------------------------------------+

3 个答案:

答案 0 :(得分:3)

尽量避免在查询中使用隐式联接

您可以尝试 EXIST 操作符,如下所示

SELECT  * 
FROM krita_db 
WHERE NOT EXISTS (
  SELECT 1 FROM sjofor_db
  WHERE krita_db.employing_nr = sjofor_db.nr)

<强> fiddle

此外,您可以使用HoàngĐăng的答案(LEFT JOIN + NULL检查)获得相同的结果

答案 1 :(得分:0)

试试这个

Select * FROM krita_db LEFT JOIN sjofor_db ON employing_nr = nr ORDER BY krita_db.id DESC

我假设complaint的表是krita_db

答案 2 :(得分:0)

您可以使用SELECT DISTINCT而不是SELECT。这将删除所有重复的行。