Reputation: 25
I have 3 tables:
I want to select total_inventories,accessory_id,supplier_id,conpany_name,phone_no
this 5 things in this three table
and the total_inventories
have to <100
and I have to use Nested Query or either standard or correlated sub-query
that is what I have done
SELECT total_inventories,accessory_id,supplier_id,conpany_name,phone_no
FROM stocktake,supplier,accessories
WHERE stocktake.accessory_id=accessory.accessory_id,accessory.supplier_id=supplier.supplier_id,
accessory_id IN (SELECT accessory_id FROM stocktake WHERE total_inventories <100)
but it got an error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'accessory.supplier_id=supplier.supplier_id,
accessory_id in (select accessory_i' at line 3
How can I fix it?
Upvotes: 0
Views: 47
Reputation: 523
You cannot use comma in where operator try. You can also refer join operation in sql.
FROM stocktake,supplier,accessories
WHERE stocktake.accessory_id=accessory.accessory_id and accessory.supplier_id=supplier.supplier_id and
accessory_id IN (SELECT accessory_id FROM stocktake WHERE total_inventories <100)
The query can be optimized as:
FROM stocktake,supplier,accessories
WHERE stocktake.accessory_id=accessory.accessory_id and accessory.supplier_id=supplier.supplier_id and
stocktake.total_inventories <100
We would not need subquery, we can directly filter total_inventories values as we have already joined three tables.
Upvotes: 1
Reputation: 7503
few things to mention in your code
you are using
accessories
table but usingaccessory.supplier_id
. so you need to use correct the table name.always use
explicit
join instead ofimplicit
joins.always use alias for the tables for more readability.
use
exists
instead ofIN
FROM stocktake s
join accessories a
on s.accessory_id = a.accessory_id
join supplier su
on a.supplier_id = su.supplier_id
WHERE a.accessory_id IN (SELECT accessory_id FROM stocktake WHERE total_inventories < 100)
In your solution you can replace IN
with exists
as following
WHERE a.accessory_id exists
(
SELECT
accessory_id
FROM stocktake s
WHERE a.accessory_id = s.accessory_id
and total_inventories < 100
)
Upvotes: 2