按两个查询排序

时间:2016-02-28 22:26:26

标签: php mysql sql

这里我对成员出版物的分类存在一些问题。

所以我有两个请求,我想用ORDER BY制作排序功能我试图制作一个ORDER BY (p.publication, pmembre.publication) ASC

但它不起作用。

这是我的功能:

function recup_publi_ami_membre()
{
    global $bdd;
    $query = $bdd->prepare("
    (   SELECT m.id_login, m.prenom, m.nom, m.affiche, m.id_admin, pmembre.publication
        FROM amis AS a
        INNER JOIN membre AS m
            ON IF(a.id_dest = :id, a.id_exp, a.id_dest) = m.id_login
        INNER JOIN publication_membre AS pmembre
            ON m.id_login = pmembre.id_auteur
        WHERE (a.id_exp = :id OR a.id_dest = :id)
            AND a.active = 1
    ) UNION (
        SELECT m.id_login, m.prenom, m.nom, m.affiche, m.id_admin, p.publication
        FROM membre AS m
        INNER JOIN publication AS p
            ON m.id_login = p.id_auteur
        WHERE m.id_login = :idget 
    )
    ");
    $query->execute(array('id' => $_GET['id'], 'idget' => $_GET['id']));
    return $query->fetchAll();
}

1 个答案:

答案 0 :(得分:0)

详细说明jkns.co's comment

将您的查询视为

(
    SELECT
        m.id_login as field1,
        m.prenom as field2,
        m.nom as field3,
        m.affiche as field4,
        m.id_admin as field5,
        pmembre.publication as field6
    FROM ...
)
UNION
(
    SELECT
        m.id_login as field1,
        m.prenom as field2,
        m.nom as field3,
        m.affiche as field4,
        m.id_admin as field5,
        p.publication as field6
    FROM ...
)

UNION为两个查询创建单个结果集,结果集包含具有fields1,...,field6的记录(all)。你可以对这个结果集进行操作,就像在一张桌子上一样(派生表,如果你过于努力的话,你可能想要"问" EXPLAIN关于性能影响。所以你可以例如做点什么

SELECT field1,field2,field3,field4,field5,field6
FROM
    (
        SELECT
            m.id_login as field1,
            m.prenom as field2,
            m.nom as field3,
            m.affiche as field4,
            m.id_admin as field5,
            pmembre.publication as field6
        FROM ...
    )
    UNION
    (
        SELECT
            m.id_login as field1,
            m.prenom as field2,
            m.nom as field3,
            m.affiche as field4,
            m.id_admin as field5,
            p.publication as field6
        FROM ...
    )
ORDER BY field6 ASC


a)你不必将工会包装在另一个SELECT ... FROM <derived table>,即快捷方式&#34; ( SELECT ... ) UNION ( SELECT ...) ORDER BY foo会这样做。

b)您不必显式设置别名以匹配字段名称; MySQL将只使用第一个UNION的名称。

所以,

( SELECT m.id_login, m.prenom, m.nom, m.affiche, m.id_admin, pmembre.publication
    FROM amis AS a
    ...
) UNION (
    SELECT m.id_login, m.prenom, m.nom, m.affiche, m.id_admin, p.publication
  FROM membre AS m
    ...
)
ORDER BY publication ASC

应该这样做。

编辑:等一下......那些字段名称​​做匹配。你确定那些应该是两个单独的表,而不是一个带有标志字段的表吗?

edit2:关于没有收到任何错误消息:由于您的代码未包含&#34;就地&#34;错误处理您可能需要switch your pdo instance to PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,例如在创建实例时:

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));