简体   繁体   中英

php mysql inner join - get a particular row

This is my query to get model information from one table and a single picture from another table. What changes do I have to make to this query in order for it to get the picture where ORDER BY sort DESC? In the table of the pictures, there is a field by the name "sort". The default value for the field for each row is 0. But one random row has the value of 1. I want to get that particular row. I don't, however, want to use WHERE sort=1 because then even in the case where no row has the sort value 1, one row should still get fetched.

    $sql="SELECT tc.id,tc.alias,tc.firstname,tci.imagename 
          FROM ".$pre."models tc
          INNER JOIN ".$pre."model_images tci ON tc.id=tci.userid 
          WHERE activated=1 AND sex=$sex AND city=$city AND published=1
          GROUP BY tc.id ORDER BY firstname ASC";

Thank you in advance!


Solved using:

    SELECT tc.id,tc.alias,tc.firstname, 
    (SELECT imagename FROM  ".$pre."model_images WHERE userid= tc.id 
    ORDER BY sort DESC LIMIT 1) AS imagename
    FROM ".$pre."models tc
    WHERE tc.activated=1 AND tc.sex=1 AND tc.city=2 AND tc.published=1
    ORDER BY tc.firstname ASC

You should place that in your WHERE clause aswell. One t hing to note though is to be carefull with the way you're using the column names. It's better to tell to which table they belong.

So this:

WHERE activated=1 AND sex=$sex AND city=$city AND published=1

Should be:

WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1

And then simply add the 'sort' column to it:

WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1 AND tci.sort=1

If no results are returned, then make sure that there are records that meet the required conditions. Because there's nothing wrong with the query. Try to print your query to the screen etc. to see if every variables has a value.

edit:

You should lose the GROUP BY.

SELECT tc.id,tc.alias,tc.firstname,tci.imagename 
FROM ".$pre."models tc
INNER JOIN ".$pre."model_images tci ON tc.id=tci.userid 
WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1 AND tci.sort=1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM