简体   繁体   中英

Select records comparing a field from another table

I have three tables

  1. orders
  2. members
  3. products

In orders, I have fields id, mem_id, date, prod_id, status where mem_id coming from members table and prod_id is coming from products table

In members, I have fields mem_id, name, phone, address, city, state, zip, country where country holds id of country from country table

Now, I want to show the records from orders table only for product id 2 and from members from country id 25

I have tried doing:

SELECT o.mem_id, o.prod_id, m.mem_id FROM orders o INNER JOIN members m ON m.mem_id = (SELECT mem_id FROM members WHERE country=25) WHERE o.prod_id=2

But it gives:

Fatal error: Call to a member function fetch_assoc() on a non-object in

So, its not fetching any data and a problem in my query. Please suggest me, Thanks

Join the table using ON condition and apply the where condition like this

SELECT o.mem_id, o.prod_id, m.mem_id
FROM orders o 
INNER JOIN members m 
ON m.mem_id = o.mem_id 
WHERE o.prod_id=2 and  m.country=25

You can JOIN the tables on column and specify the condition in WHERE clause, eg:

SELECT o.mem_id, o.prod_id, m.mem_id
FROM orders o JOIN members m ON o.mem_id = m.men_id
WHERE o.prod_id = 2 AND m.country = 25;

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