简体   繁体   English

按字母顺序显示姓名和姓氏列表

[英]Display Alphabetical order a list of name and surname

I need to display in alphabetical order a list of name and surname (order by surname). 我需要按字母顺序显示姓名和姓氏列表(按姓氏排序)。 The problem is I can't do a ORDER BY in SQL query because I retrieve my users ID in one table and retrieve the informations in another table. 问题是我无法在SQL查询中执行ORDER BY,因为我在一个表中检索了用户ID,而在另一个表中检索了信息。

My PHP code: 我的PHP代码:

$sql = "select id FROM $table_name";
$result = $wpdb->get_results($sql);
foreach ($result as $record) {
    $id = $record->id;

    $sql2 = "select field_name, field_val FROM $table_name2 where sub_id = $id";
    $result2 = $wpdb->get_results($sql2);
    foreach ($result2 as $record2) {
        if($record2->field_name == "Nom :") {
            $surname = ucfirst(stripslashes($record2->field_val));
        }
        if($record2->field_name == "Prénom :") {
            $name = ucfirst(stripslashes($record2->field_val));
        }
    }

    echo $name . " " . $surname . "<br/>";
}

Here the architecture of the second table: 这里是第二张表的架构:

f_id    sub_id      field_name      field_val
127     19          Prénom :        Philippe
128     19          Nom :           Nailloux
129     20          Prénom :        John
130     20          Nom :           Drumond

Have you an idea how I can display my list ordered by surname alphabetically? 您知道如何显示按姓氏排序的清单吗?

Thanks. 谢谢。

You can do the trick by using this SQL query : 您可以使用以下SQL查询来解决问题:

SELECT t1.id        AS user_id, 
       t2.field_val AS surname, 
       t3.field_val AS name 
FROM   $table_name t1 
       JOIN $table_name2 AS t2 
         ON ( t2.sub_id = t1.id 
              AND t2.field_name = 'Nom :' ) 
       JOIN $table_name2 AS t3 
         ON ( t3.sub_id = t1.id 
              AND t3.field_name = 'Prénom :' ) 
ORDER  BY t2.field_val 

The query will return all the infos needed (user_id, surname and name) ordered by surname. 查询将返回按姓氏排序所需的所有信息(user_id,姓氏和名称)。

Use subqueries! 使用子查询!

In your example, let's say you have 100 users. 在您的示例中,假设您有100个用户。 In first query you get your users ids, then for each user you query database for one's data. 在第一个查询中,您获取用户ID,然后为每个用户查询数据库中的数据。 That's 101 queries for a simple operation! 这是101个简单操作的查询! What if you have 10 visits per seconds? 如果您每秒访问10次该怎么办? That's more than 1000 queries. 超过1000个查询。

There are many strategies (subquery, join, two queries with in () in second one) but in this case consider that: 有许多策略(子查询,联接,第二个查询中带有in ()两个查询in () ,但在这种情况下,请考虑:

SELECT 
  field_name, field_val
FROM
  $table_name2
WHERE
  sub_id IN(
    SELECT 
      id 
    FROM 
      $table_name
  ) as sq1
ORDER BY field_val ASC;

Also consider using PHP PDO , or at least proper escaping of data you put in queries. 还可以考虑使用PHP PDO ,或者至少适当地转义查询中放入的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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