All I have table in MySQL as bellow.
+---------+-------------+---------------+ | item_no | item_name | item_location | +---------+-------------+---------------+ | ITM145 | laptop | USA | | ITM146 | camera | USA | | ITM147 | cd | USA | | ITM148 | phone | USA | | ITM149 | cd | France | | ITM150 | phone | France | +---------+-------------+---------------+
The last tow items location is France, and the same items I have in USA, I want the query to return me as bellow exclude same value for location France.
+---------+-------------+---------------+ | item_no | item_name | item_location | +---------+-------------+---------------+ | ITM145 | laptop | USA | | ITM146 | camera | USA | +---------+-------------+---------------+
First try
SELECT * FROM table WHERE item_location !='France' GROUP BY item_name
FAIL second try
SELECT * FROM table WHERE item_location NOT IN('France') GROUP BY item_name
Try this instead using the <>
operator (This is to omit 'France')
SELECT * FROM table
WHERE item_location <> 'France'
GROUP BY item_name
But if you want to get your results
SELECT * FROM table
WHERE item_location <> 'France' AND item_name IN ('laptop','camera')
GROUP BY item_name
To get the results that exclude item_name in France, you can try this
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
Try this:
SELECT * FROM table
GROUP BY item_name
Having count(*) = 1
Use LEFT JOIN
with self table like this:
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
Output:
| item_no | item_name | item_location |
|---------|-----------|---------------|
| ITM145 | laptop | USA |
| ITM146 | camera | USA |
See this SQLFiddle .
To understand joins see A Visual Explanation of SQL Joins .
您只想在其中使用“笔记本电脑”和照相机,请使用SELECT * FROM country WHERE item_location ="usa" AND (item_name = "laptop" OR item_name = "camera") GROUP BY item_no
如果您想选择
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.