开发者

Problem with SQL statement in MySQL

I am running an SQL statement:

$sql = "SELECT pic, userid 
        FROM user_details 
          INNER JOIN wp_users ON user_details.userid  
        WHERE wp_users.id = user_details.userid 
        LIMIT $recordstart, $pagesize
       ";

The query is meant to select records from user_details and wp_users, but should only select if there is a match (wp_users.id = user_details.userid).

The target is for it to basically select from a tab开发者_开发知识库le while retrieving a record (based on the id match) from the other table

The problem is that it shows duplicate records. How can I fix this problem?


You should put your JOIN condition after ON. Like this:

$sql="select pic, userid 
      from user_details 
      inner join wp_users on (wp_users.id=user_details.userid)
      limit $recordstart, $pagesize";

But the real problem is that you have more then 1 record in user_details for each corresponding record in wp_users (or vise versa). INNER JOIN is causing database to make a Cartesian product of user_details and wp_users records. Then result table is filtered by your current WHERE condition (wp_users.id=user_details.userid). Depends on your needs you can use GROUP BY or DISTINCT if you want to retrieve unique records only. For example, if you need userid to be unique:

$sql="select pic, userid 
      from user_details 
      inner join wp_users on (wp_users.id=user_details.userid)
      group by userid
      limit $recordstart, $pagesize";


SELECT DISTINCT pic, userid 
FROM user_details 
  INNER JOIN wp_users ON wp_users.id=user_details.userid 
LIMIT $recordstart, $pagesize


Use DISTINCT to return only unique rows and complete your join condition in the ON section:

$sql="select distinct pic, userid
      from user_details
      inner join wp_users on wp_users.id=user_details.userid
      limit $recordstart, $pagesize"; 


use GROUP BY , because it shows duplicate records if there is multiple records in second table per on one record in first table


You left out the = part of the ON by accident.

$sql="select pic, userid 
      from user_details 
        inner join wp_users on user_details.userid
        = wp_users.id  
      where wp_users.id=user_details.userid   
  limit $recordstart, $pagesize";


I might try

 $sql = "select pic, userid 
 from user_details 
 inner join wp_users on user_details.userid = wp_users.id
 limit $recordstart, $pagesize";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜