sql query is working but last two and condition in not giving exact answer
query:
SELECT products.*,wishlist.user_id,wishlist.p_id
FROM products
LEFT JOIN wishlist
ON products.pro_id=wishlist.p_id AND products.categ_id=2 AND wishlist.user_id=5
When you use a left join
, conditions on the first table go in the where
clause. Conditions on the second go in the on
:
SELECT p.*, wl.user_id, wl.p_id
FROM products p LEFT JOIN
wishlist wl
ON p.pro_id = wl.p_id AND wl.user_id = 5
WHERE p.categ_id = 2;
This might seem like an arcane "feature" of SQL. But it actually makes a lot of sense. The LEFT JOIN
keeps all rows in the first table, even when the ON
clause does no evaluate to true. That includes conditions on the first table. In other words, the ON
clause ignores conditions on the first table.
Your question doesn't specify what problem you are having so I will go through how to troubleshoot this.
First, this is a left join so presumably you want everything in the products table, combined with some set of things in the left join table. There's a huge difference with outer joins in the join condition vs the where clause.
Let's go over what a few permutations mean. Usually you want to take a look at these first. My recommendation is you start by changing to an inner join and see what you get. It is usually simpler to start by troubleshooting an inner join and go to the outer join after.
So start with:
SELECT products.*,wishlist.user_id,wishlist.p_id
FROM products
JOIN wishlist
ON products.pro_id=wishlist.p_id AND products.categ_id=2 AND wishlist.user_id=5
Make sure that the results are what you expect first. Then figure out what you want after. If you want all products, with Wishlist data appended to category 2 and user id, then go back to your original query. If you want products in category2 with user_id's Wishlist data then do this:
SELECT products.*,wishlist.user_id,wishlist.p_id
FROM products
LEFT JOIN wishlist
ON products.pro_id=wishlist.p_id AND wishlist.user_id=5
where products.categ_id=2
There are several other possible permutations but unless you are clear about what answers you are looking for from the database, that's the best advice I can give.
You are adding your condition in your join statement; since it's a left join that means you'll be getting results from your products table whither they matched or not.
If you want to get only results that matches your products in wishlist you'll have to change it to a where statement or use inner join instead of left join
如果可行,请尝试以下方法:
SELECT p.*, w.user_id, w.p_id FROM products p LEFT JOIN wishlist w ON p.pro_id = w.p_id WHERE p.categ_id = 2 AND w.user_id = 5
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.