mysql选择t4.name = x和t2或t3有t1.user!? :)

时间:2011-01-18 19:05:42

标签: mysql select

要解释我的问题,可以设想4个表。

users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)

产品 - (productid,product.data)

我想做一个选择,当有一个用户在产品名称上买X或产品时,会返回所有用户和产品数据。

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 product.DATA LIKE '%x%'  

这不起作用,但我相信你会明白我想做什么。

3 个答案:

答案 0 :(得分:0)

尝试如下的联盟:

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%'  

答案 1 :(得分:0)

您可以使用EXISTS子句:

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)

答案 2 :(得分:0)

非常感谢你们!

在朋友的帮助下最终做出这样的事情:


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%'