[英]SQL query ORDER BY with WHERE clause
I have 2 table. 我有2张桌子。 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). 我想按ID = 1的值或按字符串值(不是int)对订户进行排序。
For example, first, all "Journalism", secondly all "Photographer" 例如,首先是所有“新闻业”,其次是所有“摄影师”
Here is my SQL query (test) : 这是我的SQL查询(测试):
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 ... 但是此SQL查询错误会导致混合电话号码和字符串...
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: 如果要按custom_field_id = 1值进行排序,则必须在该字段上添加WHERE条件,但是您将只链接具有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: 如果您还需要选择其他自定义字段,则我认为您必须完全更改SQL,使用子查询转换列中的行,否则将为每个自定义字段获得一行:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.