SQL查询带有WHERE子句的ORDER BY

时间:2017-12-12 11:10:57

标签: mysql

我有2张桌子。第一个是订阅者的信息:

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

第二个包含自定义字段:

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

我想通过id = 1或字符串值(不是int)的值来订阅我的订阅者。

例如,首先,所有"新闻事业",其次所有"摄影师"

这是我的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

但是这个SQL查询错误导致混合电话号码和字符串......

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果要按custom_field_id = 1值排序,则必须在该字段上添加WHERE条件,但只会将该行与自定义字段= 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

如果您还需要选择其他自定义字段,我认为您必须完全更改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)