-1

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?

  • 1
    Note that `order` is a reserved word in MySQL, rendering it a poor choice as a table/column identifier. For further help, see https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query – Strawberry Sep 21 '20 at 13:38

3 Answers3

2

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
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
1

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

Laurent S.
  • 6,816
  • 2
  • 28
  • 40
0
SELECT products.productid 
LEFT JOIN `order` 
ON(products.productid=CAST(`order`.pid AS INTEGER))
WHERE `order`.pid is null;
MrFreezer
  • 1,627
  • 1
  • 10
  • 8