MySQL选择所有行,但排除相同的值

时间:2019-06-26 04:20:04

标签: mysql sql

我在MySQL中的所有表格都如下所示。

+---------+-------------+---------------+
| item_no | item_name   | item_location |
+---------+-------------+---------------+
| ITM145  |  laptop     | USA           |
| ITM146  |  camera     | USA           |
| ITM147  |  cd         | USA           |
| ITM148  |  phone      | USA           |
| ITM149  |  cd         | France        |
| ITM150  |  phone      | France        |
+---------+-------------+---------------+

最后一个拖曳项目的位置是法国,我在美国拥有的相同项目,我希望查询返回给我,因为波纹管排除了位置法国的相同值。

+---------+-------------+---------------+
| item_no | item_name   | item_location |
+---------+-------------+---------------+
| ITM145  |  laptop     | USA           |
| ITM146  |  camera     | USA           |
+---------+-------------+---------------+

第一次尝试

SELECT * FROM table
WHERE item_location !='France'
GROUP BY item_name

失败 第二次尝试

SELECT * FROM table
WHERE item_location NOT IN('France')
GROUP BY item_name

4 个答案:

答案 0 :(得分:1)

请改为使用<>运算符尝试此操作(这是为了省略“法国”)

SELECT * FROM table
WHERE item_location <> 'France'
GROUP BY item_name

但是,如果您想获得结果

SELECT * FROM table
WHERE item_location <> 'France' AND item_name IN ('laptop','camera')
GROUP BY item_name

要获得在法国排除item_name的结果,您可以尝试

SELECT * FROM table
WHERE item_location <> 'France' AND item_name NOT IN (Select item_name FROM 
table where item_location = 'France')
GROUP BY item_name

答案 1 :(得分:1)

尝试一下:

SELECT * FROM table
GROUP BY item_name
Having count(*) = 1

答案 2 :(得分:1)

LEFT JOIN与自身表一起使用:

SELECT t.* FROM Table1 t
LEFT JOIN
(
  SELECT item_name FROM Table1 WHERE item_location = 'France'
) t2
ON t.item_name = t2.item_name
WHERE t2.item_name IS NULL

输出:

| item_no | item_name | item_location |
|---------|-----------|---------------|
|  ITM145 |    laptop |           USA |
|  ITM146 |    camera |           USA |

请参阅此SQLFiddle

要了解联接,请参见A Visual Explanation of SQL Joins

答案 3 :(得分:0)

您只想让“笔记本电脑”和相机在那里使用此SELECT * FROM country WHERE item_location ="usa" AND (item_name = "laptop" OR item_name = "camera") GROUP BY item_no 如果你想选择