To explain my problem lets imagine 4 tables.
users - (userid, user.data)
buy - (buyid, productid, userid, buy.conditions)
sell - (sellid, productid, userid, sell.conditions)
product - (productid, product.data)
I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.
SELECT userid,
USER.DATA,
productid,
product.DATA
FROM users,
buy,
sell,
products
WHERE ( buy.userid = users.userid
OR sell.userid = users.userid )
AND ( buy.productid = product.productid
OR buy.productid = product.productid )
AND 开发者_JS百科product.DATA LIKE '%x%'
this doesnt work but I belive you get the idea of what I am tryng to do.
Try a union like below:
SELECT userid,
USER.DATA,
productid,
product.DATA
FROM users,
buy,
products
WHERE (buy.userid = users.userid)
AND (buy.productid = product.productid)
AND product.DATA LIKE '%x%'
UNION
SELECT userid,
USER.DATA,
productid,
product.DATA
FROM users,
sell,
products
WHERE (sell.userid = users.userid )
AND (sell.productid = product.productid )
AND product.DATA LIKE '%x%'
Thanks a lot guys!
With the help from a friend end up making something like this:
SELECT USER.DATA,
product.DATA, origem
From
(
SELECT 'b' Origem,
productid,
userid
FROM buy
union all
SELECT 's' Origem,
productid,
userid
FROM sell
) tabelas
inner join users on users.userid=tabelas.userid
inner join products on products.productid=tabelas.productid
Where product.DATA LIKE '%x%'
You could use the EXISTS clause:
SELECT userid,
USER.DATA,
productid,
product.DATA
FROM users,
products
WHERE ( EXISTS (SELECT *
FROM buy
INNER JOIN product
ON ( buy.productid = product.productid )
WHERE buy.userid = users.userid
AND product.DATA LIKE '%x%') )
OR ( EXISTS (SELECT *
FROM sell
INNER JOIN product
ON ( sell.productid = product.productid )
WHERE sell.userid = users.userid
AND product.DATA LIKE '%x%')
AND products.userid = users.userid)
精彩评论