简体   繁体   中英

SQL query ORDER BY with WHERE clause

I have 2 table. The first with the information of subscribers :

--------------------------------------------------------
| id |    first_name    |   last_name  |     mail      |
--------------------------------------------------------
| 1  |       Jean       |    Bono      | jean@bono.com |
--------------------------------------------------------
| 2  |       Paul       |     Dodu     | paule@dodu.com|
--------------------------------------------------------

The second with custom fields :

------------------------------------------------------
| id | subscriber_id | custom_field_id |   value     |
------------------------------------------------------
| 1  |       1       |        1        | Photographer  |
------------------------------------------------------
| 2  |       1       |        2        | 00000000    |
------------------------------------------------------
| 3  |       2       |        1        | Journalism|
------------------------------------------------------
| 4  |       2       |        2        | 00000000    |
------------------------------------------------------

I would like to orderby my subscribers by value where id = 1 or by string value (not int).

For example, first, all "Journalism", secondly all "Photographer"

Here is my SQL query (test) :

SELECT sub.*, cf.* 
FROM subscribers AS sub 
JOIN subscriber_custom_field AS cf 
ON cf.subscriber_id = sub.id 
WHERE sub.status = 'subscribed' 
ORDER BY cf.value

But this SQL query bug cause mix phone number and string ...

Any idea ?

Thanks !

If you want to order by custom_field_id = 1 value, then you have to add the WHERE condition on that field, but you will only link the row with custom field = 1:

SELECT sub.*, cf.value as type
FROM subscribers AS sub 
JOIN subscriber_custom_field AS cf 
ON cf.subscriber_id = sub.id 
WHERE sub.status = 'subscribed' 
AND cf.custom_field_id = 1
ORDER BY cf.value

if you need to select also the other custom fields, I think you have to fully change your SQL, transforming rows in columns using subqueries, otherwise you will obtain one row for every custom field:

SELECT sub.*, 
       (SELECT cf.value FROM subscriber_custom_field WHERE cf.subscriber_id = subscriber_id AND custom_field_id = 1) AS type,
       (SELECT cf.value FROM subscriber_custom_field WHERE cf.subscriber_id = subscriber_id AND custom_field_id = 2 LIMIT 1) AS phone
FROM subscribers AS sub 
JOIN subscriber_custom_field AS cf 
ON cf.subscriber_id = sub.id 
WHERE sub.status = 'subscribed' 
ORDER BY (SELECT cf.value FROM subscriber_custom_field WHERE cf.subscriber_id = subscriber_id AND custom_field_id = 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