繁体   English   中英

带WHERE子句的SQL查询ORDER BY

[英]SQL query ORDER BY with WHERE clause

我有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查询错误会导致混合电话号码和字符串...

任何想法 ?

谢谢 !

如果要按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

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

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