内部联接查询的唯一结果集

时间:2013-01-10 11:03:37

标签: mysql

SELECT 
    * 
FROM `catalog_webdesign_products` t 
INNER JOIN tbl_member_registration t1 ont.userid=t1.fld_loginid 
WHERE 1 
    AND t1.fld_member_category_level<9 
    AND t.product_img IS NOT NULL  
ORDER BY RAND() LIMIT 5

在此查询中,我需要具有唯一userid的行。我曾经尝试'group by userid'但是然后带有null值的product_img将进入结果集。

2 个答案:

答案 0 :(得分:2)

是的,您可以使用GROUP BY userid。但你的查询在这里看错了

   INNER JOIN tbl_member_registration t1 on t.userid=t1.fld_loginid
                                           ^------------------------space here

试试这个

  SELECT 
  * 
  FROM `catalog_webdesign_products` t 
  INNER JOIN tbl_member_registration t1 on t.userid=t1.fld_loginid 
  WHERE  t1.fld_member_category_level<9 
  AND t.product_img IS NOT NULL  
  group by userid
  ORDER BY RAND() LIMIT 5

编辑:

 SELECT 
  * 
  FROM (select * from `catalog_webdesign_products` where product_img IS NOT NULL) t 
  INNER JOIN tbl_member_registration t1 on t.userid=t1.fld_loginid 
  WHERE  t1.fld_member_category_level<9 
  group by t.userid
  ORDER BY RAND() LIMIT 5

答案 1 :(得分:0)

为了获得更好的性能,您应该将t1的条件移动到join语句中。你的问题可能是错误的JOIN条件。尝试LEFT JOIN而不是INNER JOIN。

有关加入的更多信息:http://www.w3schools.com/sql/sql_join.asp

SELECT * 
FROM `catalog_webdesign_products` t 
LEFT JOIN tbl_member_registration t1 
ON (t.userid = t1.fld_loginid AND t1.fld_member_category_level < 9)
WHERE t.product_img IS NOT NULL 
GROUP BY t.userid 
ORDER BY RAND() LIMIT 5