简体   繁体   中英

How to select all rows from a table which are not in other table?

I have 2 tables in mysql Database (mariaDB) name products and order . In product table there is column productid which is type of int(11) and set as primary key as well as auto increment. While order table has reference of productid column the name is not same and no foreign key is used. The name of column in order table is set to pid and type is varchar .

I want all the rows from products table whose productid is not present in order table.

this databases is used by an android application as well as web application. so major changes like renaming columns is not feasible.

My current approach is using programing. Get list of all productid from products and then search for them in order table one by one. This is taking a lot of time as number of products in table are about 500k Is there any other way to achieve this?

You can simply do a query to get the products:

SELECT products.productid, order.orderid 
FROM products
LEFT JOIN order ON order.pid = products.productid
WHERE order.orderid IS NULL

You might want to look into "exists" statements.

Your request would look like

SELECT * 
FROM products
WHERE 
    NOT EXISTS 
     (SELECT 1 FROM orders 
      WHERE orders.productid = products.productid);

There are other possibilities, and I'm no expert on DB to discuss further of their merits, but you can read more about that on Subqueries with EXISTS vs IN - MySQL . In my own experience (which may or may not be the same as yours) I find using "EXISTS" easier to read and performant enough

SELECT products.productid 
LEFT JOIN `order` 
ON(products.productid=CAST(`order`.pid AS INTEGER))
WHERE `order`.pid is null;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM